c++ - 如何在非类型模板类的专门化声明之外定义方法?

标签 c++ c++11 templates

标题有点啰嗦,不过基本上我是这样写的:

enum EnumType{ValA, ValB};

template<EnumType> class A {};

template<>
class A<ValA>
{
private:
    double param;
public:
    A(double param);
};

template<>
A<ValA>::A(double param)
{
    // Do Stuff
}

当我尝试编译它时,我得到:

error: template-id 'A<>' for 'A<(EnumType)0u>::A(double)' does not match any template declaration

我做错了吗?

在网上搜索了类似的案例后,我尝试去掉template<> (尽管我不明白为什么会这样),但后来我明白了

multiple definition of 'A<(EnumType)0u>::A(double)'

我想我可以替换 template<>通过 inline (我试过了,它编译了),但感觉这不是正确的方法(或者如果是,我不明白为什么)。

有人可以向我解释一下我写的东西有什么问题吗,为什么改变它似乎有效,以及正确的方法是什么?

最佳答案

Can someone explain to me what is wrong with what I wrote, why changing this seems to work, and what's the proper way to do it ?

标准说:

Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the template<> syntax.

因此,在您的情况下,您必须使用:

A<EnumType::ValA>::A(double param)
{
    // Do Stuff
}

没有template<>一切都很好。那是因为您实际上是在特化一个显式特化类模板的(特殊)成员函数(构造函数)。
coliru 上查看.


如果没有给出明确的特化,情况会有所不同。
作为一个最小的工作示例:

enum EnumType{ValA, ValB};

template<EnumType> class A
{
private:
    double param;
public:
    A(double param);
};

template<>
A<EnumType::ValA>::A(double)
{
    // Do Stuff
}

int main() {
    A<EnumType::ValA> a{0.};
}

在这种情况下,template<>在构造函数的定义之前是必需的,因为您没有定义已经专门化的类模板的成员函数的专门化。

关于c++ - 如何在非类型模板类的专门化声明之外定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42142274/

相关文章:

c++ - 检测类型是否为函数

c++ - 使用 GetWindowText 缓冲区中的错误符号

c++ - 如何为 "boost-like"多组件库编写 cmake 模块?

c++ - 如何在 C++ 中使用 cin.get() 提供更多数字?

c++ - 为什么在STL map 模板中使用模板作为参数被拒绝?

c++ - C++函数在什么情况下允许缺少模板参数?

c++ - 是否可以转发声明命名空间内的 typedef?

c++ - 在不初始化的情况下使用 STL 迭代器

c++ - make_shared如何为manager object和managed object分配单个动态内存

c++ - 正则表达式不显示 IPv6 匹配的正确结果