标题有点啰嗦,不过基本上我是这样写的:
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/