如何为类模板的内部类重载 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;
}
如果我这样编译,我会得到 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);
在struct A {
之后, 我收到链接器错误。
如果我不尝试调用 b+5,程序会正确编译。
他们(STL 制造商)是如何编程的 vector<T>::iterator operator+
用一个整数?我在任何地方都找不到它(而且它有点难以阅读 STL_vector.h)!
谢谢。
最佳答案
您面临的问题是,当您声明一个函数模板时:
template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)
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?
为了使模板推导在非推导上下文中成功,必须明确指定模板类型参数。在这种情况下,这种语法的怪异编译:
auto c = ::operator+<float>(b, 5);
但可能不是您的预期用途!
您需要申报 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;
}
};
关于内部类中的 C++ 模板运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35583018/