Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: implicit casting in templates, why it does not work?

It seems strange but this simple code works with int instead of T, and does not work with template T.

template <typename T>
class Polynomial {

public:
    Polynomial (T i) {}
    Polynomial& operator+= (const Polynomial& rhs) {
        return *this;
    }
};

template <typename T>
const Polynomial<T> operator+ (Polynomial<T> lhs_copy, const Polynomial<T>& rhs) {
    return lhs_copy += rhs;
}

Polynomial<int> x (1), y = x + 2; // no match for 'operator+' in 'x + 2'
like image 927
se0808 Avatar asked Mar 18 '23 02:03

se0808


1 Answers

Implicit conversion don't apply during template argument deduction, you might render your function friend(so that the type is known):

template <typename T>
class Polynomial {
public:
    Polynomial (T i) {};
    Polynomial& operator+= (const Polynomial& rhs) { return *this; };

    friend Polynomial operator+ (Polynomial lhs, const Polynomial& rhs) {
        return lhs+=rhs;
    }
};

Also related: C++ addition overload ambiguity

like image 153
Marco A. Avatar answered Apr 02 '23 13:04

Marco A.