模板问题:"类"类型编辑

Trouble with Templates: 'class' type redifinition

本文关键字:编辑 类型 问题      更新时间:2023-10-16
#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

我不明白这个错误的来源,如果我对这个问题有更多的了解,我会重新格式化问题,使其更清晰

如果你想为选择的类型有不同的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};    
};

这样,您就不必仅仅因为想要在特化中使用不同的枚举而重新定义所有的类成员。