Pet*_*Six 10 c++ enums metaprogramming template-meta-programming c++11
有没有办法将枚举值映射到C++中的类型,包括C++ 11.
我有以下枚举类型:
enum ATTRIBUTE{AGE=0, MENOPAUSE, TUMOR_SIZE, INV_NODES, NODE_CAPS,
DEG_MALIG, BREAST, BREAST_QUAD, IRRADIAT, CLASS};
Run Code Online (Sandbox Code Playgroud)
我想将此枚举的每个值映射到某种类型.我要地图AGE来int,MENOPAUSE另一个枚举类型,BREAST为bool等等.
那么是否可以创建一个函数来返回一个取决于attr变量值的类型值?
//Like that:
auto value = map_attr(ATTRIBUTE attr);
//Here the type of the value variable should be int if the attr variable is AGE, bool for BREAST and so on.
Run Code Online (Sandbox Code Playgroud)
sky*_*ack 17
一种惯用的方法是使用特征:
enum ATTRIBUTE{ AGE=0, MENOPAUSE, TUMOR_SIZE, INV_NODES, NODE_CAPS, DEG_MALIG, BREAST, BREAST_QUAD, IRRADIAT, CLASS };
template<ATTRIBUTE> struct Map;
template<> struct Map<AGE> {
using type = int;
static constexpr type value = 42;
};
template<> struct Map<MENOPAUSE> {
using type = AnotherEnumType;
static constexpr type value = AnotherEnumType::AnotherEnumValue;
};
// ...
Run Code Online (Sandbox Code Playgroud)
然后你可以定义map_attr为一个功能模板:
template<ATTRIBUTE A>
typename Map<A>::type map_attr() { return Map<A>::value; }
Run Code Online (Sandbox Code Playgroud)
并将其用作:
auto something = map_attr<AGE>();
Run Code Online (Sandbox Code Playgroud)
它遵循一个最小的工作示例:
#include<type_traits>
enum ATTRIBUTE{ AGE=0, MENOPAUSE };
template<ATTRIBUTE> struct Map;
template<> struct Map<AGE> {
using type = int;
static constexpr type value = 42;
};
template<> struct Map<MENOPAUSE> {
using type = double;
static constexpr type value = 0.;
};
template<ATTRIBUTE A>
typename Map<A>::type map_attr() { return Map<A>::value; }
int main() {
static_assert(std::is_same<decltype(map_attr<AGE>()), int>::value, "!");
static_assert(std::is_same<decltype(map_attr<MENOPAUSE>()), double>::value, "!");
}
Run Code Online (Sandbox Code Playgroud)