c++ - 为模板类编写二元加法运算符。编译错误

标签 c++ templates compiler-errors

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

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);
}

关于c++ - 为模板类编写二元加法运算符。编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783997/

相关文章:

c++ - 防止在 C++ 中编译未使用的模板特化

php - 使用 php 的模板?

c++ - 模板错误 : Iterator was not declared in the scope

c++ - 为什么 C++ 编译器 (gcc) 认为函数是 `virtual' 字段?

c++ - 从构造函数中捕获异常意味着我的实例之后超出了范围

c++ - 如何将缓冲区中的字符串添加到另一个数组并打印出来?

c++ - 如何在 vb.net 中非静态地使用 native dll 中的代码?

c++ - 应用warpperspective(opencv)后如何发现坐标(0,0)?

mysql - C编译器找不到头文件

c++ - 无法在 Qt 之外运行 Qt Creator GUI。 "The application was unable to start correctly (0xc000007b)"错误