我有一个班级:
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
为班级a
时,Config
的类型为a_config
type
为班级b
时,Config
的类型为b_config
枚举应该优选地保留在全局命名空间中以不破坏使用例如的现有代码。 a::Spawn(A1)
。
有没有办法实现这个目标?
答案 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
函数看起来在两种情况下都是,因为精心挑选的别名,即使这两种解决方案与概念上有很大的不同观点 - 一个需要来编辑类定义,另一个解决问题,而要求你编辑类。
选择适合您情况的解决方案。
希望有所帮助。