看起来很奇怪,但这个简单的代码使用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'
答案 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;
}
};