这是 operator+ 的尝试模板化重载。这无法同时使用 gcc 4.8 和 icc 14.0.3 进行编译。
template <typename T>
class B
{
public:
B operator+(const B& rhs)
{
return *this;
}
};
template <typename T>
class A
{
public:
operator B<T>() const{return B<T>();}
};
// template<typename T>
// B<T> operator+(A<T> const& t, A<T> const& u)
// {
// return (B<T>)t + (B<T>)u;
// }
template<typename T, typename U>
B<U> operator+(A<T> const& t, A<T> const& u)
{
return (B<U>)t + (B<U>)u;
}
int main()
{
A<double> a,b;
B<double> c = a+b;
return 0;
}
但是,注释的重载工作正常。有什么不同?为什么带有两个参数的模板不匹配?
g++48 -std=c++11 temp2.cpp
temp2.cpp: In function ‘int main()’:
temp2.cpp:33:18: error: no match for ‘operator+’ (operand types are ‘A<double>’ and ‘A<double>’)
B<double> c = a+b;
^
temp2.cpp:33:18: note: candidate is:
temp2.cpp:25:6: note: template<class T, class U> B<U> operator+(const A<T>&, const A<T>&)
B<U> operator+(A<T> const& t, A<T> const& u)
^
temp2.cpp:25:6: note: template argument deduction/substitution failed:
temp2.cpp:33:19: note: couldn't deduce template parameter ‘U’
B<double> c = a+b;
最佳答案
编译器告诉你失败的原因:
temp2.cpp:25:6: note: template argument deduction/substitution failed:
temp2.cpp:33:19: note: couldn't deduce template parameter ‘U’
模板参数U
只出现在函数模板的返回类型中,因此无法推导。如果您显式列出模板参数,您的代码将编译
B<double> c = operator+<double, double>(a, b);
如果您交换模板参数的顺序,使 U
出现在 T
之前,您仍然可以推导 T
。
template<typename U, typename T>
B<U> operator+(A<T> const& t, A<T> const& u)
{
return (B<U>)t + (B<U>)u;
}
B<double> c = operator+<double>(a, b);
注释掉的 operator+
实现有效,因为返回类型也使用相同类型的参数 T
,因此可以从函数模板参数中推导出它。
关于c++ - 定义模板化运算符重载时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24194765/