【发布时间】:2015-01-27 16:43:38
【问题描述】:
我有一个模板向量类,我正在尝试重载算术运算符,以便添加/减去不同原始类型的向量将产生算术运算返回的原始类型的向量(即添加一个 int 向量一个双精度向量将产生一个双精度向量)。相关代码如下:
template<typename T>
class Vector {
private:
T x, y, z;
public:
// constructors, destructors, etc.
T X() const { return ( this->x ); }
T Y() const { return ( this->y ); }
T Z() const { return ( this->z ); }
template<typename U> auto operator+(const Vector<U> &v) const -> Vector<decltype(this->x + v.X())>
{
return ( Vector<decltype(this->x + v.X())>( this->x + v.X(), this->y + v.Y(), this->z + v.Z() ) );
}
};
然后,在 main.cpp 中:
Vector<double> d1(1,2,3), d2(4,5,6);
std::cout << d1 + d2;
我从 Visual Studio 2012 收到以下错误:
error C2893: Failed to specialize function template 'Vector<T> Vector<double>::operator +(const Vector<U> &) const'
with
[
T=unknown
]
With the following template arguments:
'double'
error C2676: binary '+' : 'Vector<T>' does not define this operator or a conversion to a type acceptable to the predefined operator
with
[
T=double
]
请指教。
【问题讨论】:
-
尝试升级到visual-studio-2013。适用于 gcc (ideone.com/GlJOcE)
标签: c++ templates visual-studio-2012 c++11