简体   繁体   English

无法专门化功能模板编译器错误

[英]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 (ie, adding a vector of int and a vector of double will yield a vector of double). 我有一个模板矢量类,并且我试图重载算术运算符,以便将不同原始类型的矢量相加/减去将得出算术运算返回的原始类型的矢量(即,将int和vector相加的double将产生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: 然后,在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: 我从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. 请指教。

Visual C++ fails to determine the correct type of your decltype expression. Visual C ++无法确定正确的decltype表达式类型。 By replacing your expression with decltype(*((T*)0) + *((U*)0)) you remove the dependency on this and the argument v , which leads to the intended result on VS as well. 通过用decltype(*((T*)0) + *((U*)0))替换表达式,可以删除this和参数v的依赖, this也将导致VS的预期结果。

Note: Bug was reproducable on VS2013.4 on which the fix was tested as well. 注意:该错误在经过测试的VS2013.4上也可以再现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM