【发布时间】:2014-06-12 22:17:24
【问题描述】:
这是一个尝试的 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;
【问题讨论】:
-
“编译失败”是否意味着您收到错误消息?错误信息是什么?
-
"
couldn't deduce template parameter ‘U’" 对我来说似乎很清楚 -
不相关,我不明白你为什么用两个模板参数编写版本,除非它们相同,否则它不会编译/工作。
-
您认为
U是如何推导出来的? -
只是为了好玩:您可以实际上模拟返回类型的重载。请参阅实际编译的this example。将它推广到像
a+(2*b)/c这样的表达式更复杂(尽管并非不可能;)
标签: c++ templates c++11 operator-overloading