[英]C++ - mapping type to enum
Is is possible to make compilation-time Type -> Enum Series
mapping? 是否可以在编译时进行
Type -> Enum Series
映射?
Illustrating with an example: 举例说明:
Let's say, I have some Type
and a enumerated value: 假设我有一些
Type
和一个枚举值:
typedef int Type;
enum Enumerated { Enum1, Enum2, Enum3, Enum4 };
and now I somehow state the following: "let's associate Enum1
and Enum4
with type Type
(don't know how to implement this yet). 现在,我以某种方式声明以下内容: “让我们将
Enum1
和Enum4
与Type
关联(尚不知道如何实现)。
Now I want to be able to check the following (better to be done using mpl in compilation time): 现在,我希望能够检查以下内容(最好在编译时使用mpl来完成):
If some arbitrary type and enum are actually being mapped to each other: 如果实际上将某些任意类型和枚举相互映射:
template <typename ArbitraryType, Enumerated E>
struct check_at_compile_time {
// Somehow tricky evaluate this
static const bool value;
};
so that the results are the following: 因此结果如下:
check_at_compile_time<Type, Enum1>::value evaluates to TRUE
check_at_compile_time<Type, Enum2>::value evaluates to FALSE
check_at_compile_time<Type, Enum4>::value evaluates to TRUE
check_at_compile_time<int, Enum3>::value evaluates to FALSE
If someone knows a nice way to implement this, please help me. 如果有人知道实现此目标的好方法,请帮助我。 Maybe something using
boost::mpl
, I'm not sure. 也许使用
boost::mpl
,我不确定。
Thanks. 谢谢。
You can do it this way even without boost.mpl: 即使没有boost.mpl,您也可以通过这种方式进行操作:
template< Enumerated Value > struct Enumerated2Type { typedef void type; enum { value = false }; };
#define DEFINE_ENUMERATED_TYPE(TYPE, ENUM) template<> struct Enumerated2Type<ENUM> { typedef TYPE type; enum { value = true }; }
DEFINE_ENUMERATED_TYPE(int, Enum1);
DEFINE_ENUMERATED_TYPE(bool, Enum2);
DEFINE_ENUMERATED_TYPE(double, Enum3);
DEFINE_ENUMERATED_TYPE(std::string, Enum4);
And you check you can do this way: 然后检查您可以这样做:
template <typename ArbitraryType, Enumerated E>
struct check_at_compile_time {
static bool const value = Enumerated2Type< E >::value && boost::is_same< ArbitraryType, typename Enumerated2Type< E >::type >::value;
};
Untested but should work like this. 未经测试,但应该像这样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.