Mig*_*uel 5 c++ templates operator-overloading
如何为类模板的内部类重载 operator+?我已经搜索了几个小时,但找不到答案。这是一个不起作用的最小示例:
#include <iostream>
using namespace std;
template <class T>
struct A
{
struct B
{
T m_t;
B(T t) : m_t(t) {}
};
};
template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)
{
lhs.m_t += n;
return lhs;
}
int main(int argc, char **argv)
{
A<float> a;
A<float>::B b(17.2);
auto c = b + 5;
cout << c.m_t << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我这样编译,我得到 error: no match for ‘operator+’ (operand types are ‘A<float>::B’ and ‘int’)
我找到了operator+(A<T>::B, int)应该声明的地方,所以如果我添加以下内容:
struct B;
friend B operator+(typename A<T>::B lhs, int n);
Run Code Online (Sandbox Code Playgroud)
之后struct A {,我收到链接器错误。
如果我不尝试调用 b+5,程序将正确编译。
他们(STL 制造商)是如何vector<T>::iterator operator+用 int编程的?我在任何地方都找不到它(而且很难阅读 stl_vector.h)!
谢谢你。
您面临的问题是,当您声明如下函数模板时:
template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)
Run Code Online (Sandbox Code Playgroud)
typename A<T>::B lhs是一个非推导的上下文。编译器无法确定T该上下文中的内容,因此它不会尝试,因此无法找到您的operator+. 考虑一个简化的例子,例如:
template <class T> void foo(typename T::type );
struct A { using type = int; };
struct B { using type = int; };
foo(0); // what would T be?
// how many other possible T's are there that fit?
Run Code Online (Sandbox Code Playgroud)
为了使模板推导能够在非推导上下文中成功,必须显式指定模板类型参数。在这种情况下,这种可怕的语法会编译:
auto c = ::operator+<float>(b, 5);
Run Code Online (Sandbox Code Playgroud)
但可能不是您的预期用途!
您需要声明以下operator+内容struct B:
struct B
{
T m_t;
B(T t) : m_t(t) {}
// member
B operator+(int n) {
return B(m_t + n);
}
// or non-member, non-template friend
friend B operator+(B lhs, int n) {
lhs.m_t += n;
return lhs;
}
};
Run Code Online (Sandbox Code Playgroud)