Select 基于模板参数的枚举类型
Select enum type based on template parameter
我有一个 class:
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.
类 a
、b
等(源自 sysbase
)将作为 type
模板参数传递给 sysbase
.
现在我想将 Config
参数更改为其中一种枚举类型,而不仅仅是普通的 int 以提高类型安全性,因此:
- 当
type
为 class a
时,Config
的类型将为 a_config
- 当
type
为 class b
时,Config
的类型将为 b_config
- 等等
枚举最好保留在全局命名空间中,以免破坏使用例如a::Spawn(A1)
.
有办法做到这一点吗?
侵入式解决方案:将classes中enum-types的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
函数 看起来 在这两种情况下都一样 因为 精心选择的别名,即使这两个解决方案从概念的角度来看非常不同 — 一个 需要 编辑 class 定义,另一个解决问题 没有 要求您编辑 classes.
选择适合您情况的解决方案。
希望对您有所帮助。
我有一个 class:
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.
类 a
、b
等(源自 sysbase
)将作为 type
模板参数传递给 sysbase
.
现在我想将 Config
参数更改为其中一种枚举类型,而不仅仅是普通的 int 以提高类型安全性,因此:
- 当
type
为 classa
时,Config
的类型将为a_config
- 当
type
为 classb
时,Config
的类型将为b_config
- 等等
枚举最好保留在全局命名空间中,以免破坏使用例如a::Spawn(A1)
.
有办法做到这一点吗?
侵入式解决方案:将classes中enum-types的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
函数 看起来 在这两种情况下都一样 因为 精心选择的别名,即使这两个解决方案从概念的角度来看非常不同 — 一个 需要 编辑 class 定义,另一个解决问题 没有 要求您编辑 classes.
选择适合您情况的解决方案。
希望对您有所帮助。