Nikita Bobko
Nikita Bobko

Reputation: 624

Writing binary addition operator for template class. Compilation error

Cannot correctly code operator+ for template class using friend function. Only one question: why compilation error? And how to fix it?

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++ outputs:

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
         ^

Upvotes: 0

Views: 65

Answers (1)

Barmar
Barmar

Reputation: 780889

The operator+ method should use A<T>, not its own template.

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

Upvotes: 2

Related Questions