Pra*_*han 1 c++ templates operator-overloading c++11
这是运算符+的模拟重载过载.这无法使用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;
}
Run Code Online (Sandbox Code Playgroud)
但是,评论的重载工作正常.有什么不同?为什么两个参数的模板不匹配?
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;
Run Code Online (Sandbox Code Playgroud)
编译器告诉你失败的原因:
temp2.cpp:25:6:注意:模板参数推断/替换失败:
temp2.cpp:33:19:注意:无法推导出模板参数'U'
模板参数U仅出现在函数模板的返回类型中,因此无法推导出.如果明确列出模板参数,您的代码将编译
B<double> c = operator+<double, double>(a, b);
Run Code Online (Sandbox Code Playgroud)
如果您交换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);
Run Code Online (Sandbox Code Playgroud)
注释掉的operator+实现是有效的,因为返回类型也使用相同的类型参数T,因此允许从函数模板参数推导出它.
在
B<double> c = a+b;
Run Code Online (Sandbox Code Playgroud)
类型模板参数U中
B<U> operator+(A<T> const& t, A<T> const& u)
Run Code Online (Sandbox Code Playgroud)
无法推断.U不会double简单地推断出因为呼叫的结果被分配给B<double>.您必须明确指定U为double,例如,通过以下方式,
B<double> c = operator+<double, double>(a, b);
Run Code Online (Sandbox Code Playgroud)
现在显然这可能不是一个理想的情况.所以,你可以做什么?嗯,很难说,因为你没有说明什么A和B将要用于.但是,正如您已经发现的那样,您的代码将使用已注释掉的运算符进行编译,
template<typename T>
B<T> operator+(A<T> const& t, A<T> const& u)
{
return (B<T>)t + (B<T>)u;
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,你似乎希望它是可以使用的结果来初始化一个B<U>地方U可能不一样T,所以也许是正确的解决方案是使其可以构建B<U>来自B<T>:
template <typename T>
class B
{
public:
template <typename U>
B(const B<U>& rhs) {
// ...
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
(您可能还想编写类似的赋值运算符.)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |