se0808
se0808

Reputation: 596

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'

Upvotes: 4

Views: 186

Answers (1)

Marco A.
Marco A.

Reputation: 43662

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

Upvotes: 7

Related Questions