【发布时间】:2011-11-09 02:14:01
【问题描述】:
我有一个定义运算符的模板类,它适用于模板参数。 我有另一个从这个类继承的类,我当然希望运算符被继承。
考虑一下:
template <typename T>
class A
{
public:
A(const T& x) : x_(x) {}
A operator-(const A& other)
{
A r(*this);
r.x_ -= other.x_;
return r;
}
T x() const { return x_; }
private:
T x_;
};
template <typename T>
class B : public A<T>
{
// additional stuff here
};
我似乎无法将 A 中声明的任何运算符用于 B 类型的对象。
例子:
int main()
{
// Fine
A<int> a(5);
A<int> b(2);
A<int> c = a - b;
std::cout << c.x() << std::endl;
// Won't compile :(
B<int> d(5);
B<int> e(2);
B<int> f = d - e;
std::cout << f.x() << std::endl;
return 0;
}
将触发以下错误:错误:请求从“A”转换为非标量类型“B”
有什么办法可以做到吗?我真的很想避免在 B 类中重写所有代码(这将是完全相同的)。
谢谢!
【问题讨论】: