使用模板进行重载运算符

3

我有一个类,必须能够容纳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很大,类型就需要改变。

但是,我似乎找不到一个好的解决办法。我会非常感谢您的建议。谢谢。

3个回答

7
你需要将operator+=也变成一个模板:

template <typename T>
class F{
public:
       F(const T & t){ a = t; }
       T a;

       template<typename T2>
       F& operator+=(const F<T2>& rhs);
}; // semicolon was missing

template<typename T>
template<typename T2>
F<T>& F<T>::operator+=(const F<T2>& rhs) {
       a += rhs.a;
       return *this; // semicolon was missing
} // brace was missing

然后您可以执行:
F<int> a(4);
F<float> b(28.4);

b += a;

cout << b.a << endl; // prints 32.4

这里是一个可行的示例


谢谢Seth,我先尝试了moka的答案,然后在我的代码中尝试了你的修改,但它无法编译。感谢你的回答,我相信我现在知道原因了。由于我的代码非常大,我将其分成头文件和实现文件,并使用声明我将在实现文件中使用的模板的技巧,即template class F<float>;和template class F<int>;但忘记为函数提供一个。 现在我正在努力创建一个,我认为应该是这样的: template Variable<double> Variable<double>::operator+=(const Variable<float> & other); 但那行不通。 - wookie1
2
@wookie1,我认为你的注释中缺少一个&template Variable<double>& Variable<double>::operator+=(const Variable<float> & other); - Aaron McDaid
啊,我真傻,一直尝试各种组合来让它工作,谢谢。 - wookie1

1
    template <typename T>
    class F{
    public:
           F(const T & t){a=t;}
           T a;
           template<typename T2>
           F & operator+= (const F<T2> & rhs);
    };

    template<typename T>
    template<typename T2>
    F<T>& F<T>::operator+= (const F<T2> & rhs){
           a+=(T)rhs.a;
           return *this
    }

编辑:

已修复错误,请参见评论。


这是正确的想法,但它无法编译;请参考@Seth的答案。 - Oliver Charlesworth
你的意思是因为有 template<typename T, typename T2> 这一部分吗? - moka

0

您可以将operator+=进行模板化:

template<typename G> F<T> & operator+= (const F<G> & rhs);

假设你可以以某种方式将 G 转换为 T


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接