C++ - mapping type to enum
Is is possible to make compilation-time Type -> Enum Series
mapping?
Illustrating with an example:
Let's say, I have some Type
and a enumerated value:
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 ye开发者_开发技巧t).
Now I want to be able to check the following (better to be done using mpl in compilation time):
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.
Thanks.
You can do it this way even without 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.
精彩评论