具有运算符重载的模板类

Template class with operator overload

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

这是我关于模板类的问题

aclass<int> A{1,2};
aclass<float> B{3.0,4.0};
aclass<int> C;
int main()
{
  C=A+B;   //How to overload this operator in a simple way?
  B=A;   //And also this?
  return 0;
}

如何重载运算符来处理不同类型的模板类?(对不起,我的英语不好)

可以在

类模板中包含成员函数模板:

template <typename T>
struct aclass
{
    aclass(aclass const &) = default;
    aclass & operator=(const aclass &) = default;
    template <typename U>
    aclass(aclass<U> const & rhs) : a_(rhs.a_), b_(rhs.b_) {}
    template <typename U>
    aclass & operator=(aclass<U> const & rhs)
    {
        a_ = rhs.a_;
        b_ = rhs.b_;
        return *this;
    }
    T a_, b_;
};