c++ - 特殊类模板的类外构造函数定义

标签 c++ templates template-specialization

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

template <typename T>
struct x;

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

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

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

不过好像是报错了。 Comeau 说:error: "x<int>::x()" is not an entity that can be explicitly specialized ,即使完整的类是特化的。

这里有什么问题?

最佳答案

不要指定 template<>对于定义:

template <typename T>
struct x;

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

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

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

关于c++ - 特殊类模板的类外构造函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3935916/

相关文章:

c++ - Understanding floating point variables and operators in c++(也可能是书上的错误)

c++ - 如何使用模板将 lambda 转换为 std::function

c++ - 仅在头文件中静态模板化成员函数的模板行为

c++ - 这是管理 COM 初始化的好方法吗?

c++ - 关于别名模板

c++ - 如何在 linux 平台上使用 openGL glDebugOutput/glDebugMessageCallback

templates - 在 Joomla 2.5 中,如何在模板中回显文章的 "Link A"值?

模板类的实例化对象上的 C++ 模板元函数

c++ - 使用模板参数作为模板参数

c++ - 具有非类型模板参数的函数模板中的 static_assert