根据模板参数选择枚举类型

时间:2015-06-29 13:46:01

标签: c++ templates c++11 enums refactoring

我有一个班级:

template <class type>
class sysbase : public base
{
 public:
  static type* Spawn(int Config = 0) { … }
  … 
};

全局命名空间中有大约50个枚举:

enum a_config { A1, A2, … };
enum b_config { B1, B2, … };
etc.

ab等(源自sysbase)将作为type模板参数传递给sysbase

现在我想将Config参数更改为其中一个枚举类型,而不仅仅是一个普通的int来改善类型安全性,以便:

  • type为班级a时,Config的类型为a_config
  • type为班级b时,Config的类型为b_config

枚举应该优选地保留在全局命名空间中以不破坏使用例如的现有代码。 a::Spawn(A1)

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:6)

  • 侵入式解决方案:将类中的枚举类型的typedef定义为成员,并将其作为typename type::enum_type访问:

    class a
    {
       public:
           using enum_type = a_config; //C++11 style typedef
    };
    
    //define all such classes in the same way.
    
    //lets also define a friendly template alias to access the enum type.
    template<typename T>
    using enum_type = typename T::enum_type;
    
    //then you could define Spawn as
    static type* Spawn(enum_type<T> config) { … }
    
  • 非侵入式解决方案:定义将类型映射到枚举的类型特征,并将其用作typename enum_type_<type>::type

     template<typename>
     struct enum_type_;  //primary template (no definition)
    
     //specialize enum_type_ for each class type as:
     template<> 
     struct enum_type_<a>
     { 
        using type = a_config; 
     };
    
     //now define the alias as
     template<typename T>
     using enum_type = typename enum_type_<T>::type;
    
    //then you could define Spawn as
    static type* Spawn(enum_type<T> config) { … }
    

嗯,你的Spawn函数看起来在两种情况下都是,因为精心挑选的别名,即使这两种解决方案与概念上有很大的不同观点 - 一个需要来编辑类定义,另一个解决问题,而要求你编辑类。

选择适合您情况的解决方案。

希望有所帮助。