使用模板重载运算符

operator overloading with templates

本文关键字:重载 运算符      更新时间:2023-10-16

我有一个类,它必须能够容纳一种浮点数,双精度,长超型。我想以这样一种方式重载它,以便它可以添加两个持有不同类型的实例。

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 += 只要的操作时存在潜在问题,因为如果长型很大,则需要更改类型。我似乎找不到解决问题的好方法。感谢您的投入。谢谢

还需要将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

这是一个工作示例。

    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
    }

编辑:

修复错误,请参阅评论

> 你可以模板化operator+=

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

。假设您可以以某种方式将G转换为T.