将枚举值映射到 C++ 中的类型 [英] Map enum value to a type in C++
问题描述
有没有办法将枚举值映射到 C++ 中的类型,包括 C++11.
我有以下枚举类型:
Is there any way to map enum values to types in C++, including C++11.
I have the following enum type:
enum ATTRIBUTE{AGE=0, MENOPAUSE, TUMOR_SIZE, INV_NODES, NODE_CAPS,
DEG_MALIG, BREAST, BREAST_QUAD, IRRADIAT, CLASS};
我想将此枚举的每个值映射到特定类型.我想将 AGE
映射到 int
,MENOPAUSE
映射到另一个枚举类型,BREAST
映射到 bool 等等.
那么是否有可能创建一个函数来返回一个取决于 attr 变量值的类型值?
I want to map each value of this enum to a certain type. I want to map AGE
to int
, MENOPAUSE
to another enum type, BREAST
to bool and so on.
So is it possible to create a function which returns a value of type which depends on the value of the attr variable?
//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.
推荐答案
一种惯用的方式是使用特性:
An idiomatic way to do it is using traits:
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;
};
// ...
然后你可以定义map_attr
作为一个函数模板:
Then you can define map_attr
as a function template:
template<ATTRIBUTE A>
typename Map<A>::type map_attr() { return Map<A>::value; }
并将其用作:
auto something = map_attr<AGE>();
<小时>
它遵循一个最小的工作示例:
It follows a minimal, working example:
#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, "!");
}
这篇关于将枚举值映射到 C++ 中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!