我有一个类,必须能够容纳float、double、long等类型。我希望以这样的方式重载它,使它能够添加持有不同类型的两个实例。
template <typename T>
class F{
public:
F(const T & t){a=t;}
T a;
F & operator+= (const F & rhs);
}
template<typename T>
F<T> F::operator+= (const F & rhs){
a+=rhs.a;
return *this
这只是我保留了无关部分的伪代码,实际上我正在尝试使用这种解决方案。
现在当尝试使用时:
F<int> first(5);
F<int> second(4);
first+=second; // Works
F<int> third(5);
F<float> fourth(6.2);
fourth+=third; // wont work
我能理解为什么这个方法不起作用,因为它假设rhs参数与lhs参数是相同类型的。我也能看到执行int += long操作可能存在潜在问题,因为如果long很大,类型就需要改变。
但是,我似乎找不到一个好的解决办法。我会非常感谢您的建议。谢谢。
&
。template Variable<double>& Variable<double>::operator+=(const Variable<float> & other);
- Aaron McDaid