为模板类编写二进制加法运算符. 编译错误

Writing binary addition operator for template class. Compilation error

本文关键字:运算符 编译 错误 二进制      更新时间:2023-10-16

无法使用友元函数为模板类正确编码运算符+。只有一个问题:为什么编译错误?以及如何解决它?

template <typename T>
class A {
    T a;
public:
    A(T a) : a(a) {
    }
    template<typename K>
    friend A<K> operator +(const A<K> &a, const A<K> &b) {
        return A<K>(a.a + b.a);
    }
};
int main(int argc, const char **argv) {
    A<int> a(1);
    A<int> b(2);
    a + b;          // no compilation error
    (A<int>)1 + a;  // no compilation error
    1 + a;          // compilation error
    return 0;
}

G++ 输出:

07-04.cpp: In function ‘int main(int, const char**)’:
07-04.cpp:20:7: error: no match for ‘operator+’ (operand types are ‘int’ and ‘A<int>’)
     1 + a;          // compilation error
       ^
07-04.cpp:10:17: note: candidate: template<class K> A<K> operator+(const A<K>&, const A<K>&)
     friend A<K> operator +(const A<K> &a, const A<K> &b) {
                 ^
07-04.cpp:10:17: note:   template argument deduction/substitution failed:
07-04.cpp:20:9: note:   mismatched types ‘const A<K>’ and ‘int’
     1 + a;          // compilation error
         ^

operator+ 方法应该使用 A<T> ,而不是它自己的模板。

friend A<T> operator +(const A<T> &a, const A<T> &b) {
    return A<T>(a.a + b.a);
}