模板问题:'类'类型重定义

时间:2016-09-24 12:05:49

标签: c++ templates

#pragma once
//includes
template<class RefType>
class Foo
{
public:

 template<>
 enum  Foo<QString>::bar { //values A }; //LINE X
 template<>
 enum Foo<double>::bar { //values B };
 template<>
 enum Foo<Kraken::Point3>::bar { //values C };
//functions
}; //LINE Y

编译器为LINE X提供错误

error C2011: 'Foo<QString>': 'class' type redefinition 

附注

note: see declaration of 'Foo<QString>' LINE X
note: note: see reference to class template instantiation 'Foo<RefType>'LINE Y

我不明白这个错误的根源,如果我对这个问题变得更加开明,我会重新格式化问题以使其更清晰

1 个答案:

答案 0 :(得分:0)

如果您希望为所选类型设置不同的enum,则应使用以下类型对模板类进行专门化:

template<class RefType>
class Foo
{
    //default enum if you want
};

template<>
class Foo<QString>
{
    enum bar {Q1, Q2, Q3};    
};

template<>
class Foo<double>
{
    enum bar {d1, d2, d3};    
};

template<>
class Foo<Kraken::Point3>
{
    enum bar {K1, K2, K3};    
};

您的代码看起来想要专门化一些类模板的成员,但这在C ++中是不可能的。

在保留大部分类结构的同时破解这种方法的一种方法是通用类实现的公共继承:

template<class Reftype>
class FooImpl
{
    RefType x;
public:
    void set_x(RefType val) {x=val;}
    RefType get_x(void) {return x;}
};

template<class RefType>
class Foo : public FooImpl<Reftype>
{

};

template<>
class Foo<QString> : public FooImpl<QString>
{
    enum bar {Q1, Q2, Q3};    
};

template<>
class Foo<double> : public FooImpl<double>
{
    enum bar {d1, d2, d3};    
};

template<>
class Foo<Kraken::Point3> : public FooImpl<Kraken::Point3>
{
    enum bar {K1, K2, K3};    
};

这样您就不必重新定义所有类成员,因为您需要专业化中的不同枚举。

相关问题