【发布时间】:2016-02-23 16:34:47
【问题描述】:
如何为类模板的内部类重载 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 制造商)如何使用 int 对 vector<T>::iterator operator+ 进行编程?我在任何地方都找不到它(而且有点难以阅读 stl_vector.h)!
谢谢。
【问题讨论】:
-
没有继承,你所谓的“子”类我宁愿叫“内”/“嵌套”类
-
您是否尝试将运算符作为成员函数?
-
Tintypename A<T>::B lhs是不可演绎的,因此此重载对于调用不可行
标签: c++ templates operator-overloading