C ++:在模板中隐式转换,为什么它不起作用?

时间:2014-10-24 16:48:05

标签: c++ templates casting

看起来很奇怪,但这个简单的代码使用int而不是T,并且不适用于模板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'

1 个答案:

答案 0 :(得分:7)

隐式转换在模板参数推导期间不适用,您可以渲染函数friend(以便知道类型):

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

还相关:C++ addition overload ambiguity