2

是否可以进行编译时Type -> Enum Series映射?

用一个例子来说明:

比方说,我有一些Type枚举值:

typedef int Type;

enum Enumerated { Enum1, Enum2, Enum3, Enum4 };

现在我以某种方式声明以下内容:“让我们Enum1Enum4 类型关联Type (还不知道如何实现)。


现在我希望能够检查以下内容(最好在编译时使用 mpl 来完成):

如果某些任意类型和枚举实际上正在相互映射:

template <typename ArbitraryType, Enumerated E>
struct check_at_compile_time {
   // Somehow tricky evaluate this
   static const bool value;
};

所以结果如下:

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

如果有人知道实现这一点的好方法,请帮助我。也许使用的东西boost::mpl,我不确定。

谢谢。

4

1 回答 1

5

即使没有 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);

你检查你可以这样做:

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;
};

未经测试,但应该像这样工作。

于 2010-10-12T12:23:43.893 回答