【问题标题】:Failed to specialize function template compiler error无法专门化函数模板编译器错误
【发布时间】: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
]

请指教。

【问题讨论】:

标签: c++ templates visual-studio-2012 c++11


【解决方案1】:

Visual C++ 无法确定decltype 表达式的正确类型。通过用decltype(*((T*)0) + *((U*)0)) 替换你的表达式,你删除了对this 和参数v 的依赖,这也导致了VS 上的预期结果。

注意:在 VS2013.4 上也可以重现错误,该修复也经过测试。

【讨论】:

  • 谢谢!这样可行。我对你在这里的表达感到困惑;你能解释一下它的含义吗?
  • @LRC 它取消引用适当类型的(空)指针以分别创建TU 的左值。这样,它们就不需要以任何特定方式构造。
  • 感谢您的解释!这很有道理!
  • decltype(std::declval&lt;T&gt;() + std::declval&lt;U&gt;()) 似乎更具可读性。
  • @Jarod42 我同意,我只是懒得弄清楚 VS2012 是否已经支持 declval
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多