【问题标题】:Out of class constructor definition for a specialized class template专用类模板的类外构造函数定义
【发布时间】:2010-10-14 17:38:42
【问题描述】:

我正在尝试为类定义之外的显式专用类模板定义构造函数,如下所示:

template <typename T>
struct x;

template <>
struct x<int> {
    inline x();

    /* This would have compiled:
    x() {
    }
    */
};

template <>    // Error
x<int>::x() {
}

但这似乎是一个错误。 Comeau 说:error: "x&lt;int&gt;::x()" is not an entity that can be explicitly specialized,尽管完整的课程是专门的。

这里有什么问题?

【问题讨论】:

  • 我以前从未见过这个。在这里知道答案会很有趣。不过,一般来说,我会保持我的模板内联编码,以减少所有不必要的混乱。
  • 使用 g++,我收到错误 template-id ‘x&lt;&gt;’ for ‘x&lt;int&gt;::x()’ does not match any template declaration。但是,如果我将其更改为不是构造函数,我仍然会收到等效错误:template-id ‘pants&lt;&gt;’ for ‘void x&lt;int&gt;::pants()’ does not match any template declaration.
  • @Josh D:当然可以。事实上,对于没有有意义的泛型定义的 char_traits&lt;&gt; 风格的类来说,这是唯一的选择 - 未定义特化的类参数将产生编译错误。
  • @Steve M. 我被误导了。谢谢你纠正我。冒犯性的谎言已被删除。

标签: c++ templates template-specialization


【解决方案1】:

不要为定义指定template&lt;&gt;

template <typename T>
struct x;

template <>
struct x<int> {
  x();
};

inline x<int>::x(){}

编辑:构造函数定义不是特化的,所以template&lt;&gt; 是不必要的。它是专业化构造函数的定义。因此,您只需要像任何其他非模板类一样指定类型。

【讨论】:

  • 没想到要删除模板声明。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 2015-03-12
相关资源
最近更新 更多