在重载运算符上支持不同类型?

时间:2015-01-12 01:50:37

标签: c++

我怀疑,为不同类型的自定义类支持运算符是正确的吗? 假设我们有这个:

template<class T>
class C { /* Class implemantation */ }

int main () {

    C<int> someObject;
    C<double> otherObject;

    std::cout << someObject + otherObject;

}

支持运算符+对于C对象类型为int和类型为double的C对象是否正确?

2 个答案:

答案 0 :(得分:2)

是否或在逻辑上正确取决于您(班级设计师)希望如何使用您的课程。添加someObjectotherObject是否合乎逻辑?添加23.5是有意义的,但这并不能说明代码是否合适。作为一个反例,您无法添加basic_string<char>basic_string<wchar> - 由于您必须存储相同类型的字符,因此添加不会有意义 - 但您可以< / em>为任何basic_string<T>添加两个T

您可以编写代码来执行此操作,并确定??

template <typename T>
class C {
    ..
    template <typename U>
    C<??> operator+(const C<U>& rhs) {
        // ..
    }
};

答案 1 :(得分:0)

如果您希望特定运算符针对某些类型对您的类的特化进行操作,则始终可以编写专门的运算符重载,例如:

template<class T>
class C { /* implementation */ };

C<double> operator+ (C<int> a, C<double> b)
{
  C<double> ret;
  // Do something to ret given a and b
  return ret;
}

// Lets make it commutative (is that the right word?)
C<double> operator+ (C<double> a, C<int> b)
{
  return b + a;
}

int main(int argc, char** argv)
{
  C<int> a;
  C<double> b;

  C<double> ret1 = a + b;
  C<double> ret2 = b + a;

  return 0;
}

这取决于你想要达到的行为。