mardi 27 janvier 2015

Failed to specialize function template compiler error

I have a template vector class, and I am trying to overload the arithmetic operators such that adding/subtracting vectors of different primitive types will yield a vector of the primitive type returned by the arithmetic operation (i.e., adding a vector of int and a vector of double will yield a vector of double). The relevant code follows:



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() ) );
}
};


Then, in main.cpp:



Vector<double> d1(1,2,3), d2(4,5,6);
std::cout << d1 + d2;


I get the following error from 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
]


Please advise.


Aucun commentaire:

Enregistrer un commentaire