gpt4 book ai didi

c++ - 将枚举值映射到 C++ 中的类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:08:00 33 4
gpt4 key购买 nike

有什么方法可以将枚举值映射到 C++ 中的类型,包括 C++11。
我有以下枚举类型:

enum ATTRIBUTE{AGE=0, MENOPAUSE, TUMOR_SIZE, INV_NODES, NODE_CAPS,
DEG_MALIG, BREAST, BREAST_QUAD, IRRADIAT, CLASS};

我想将此枚举的每个值映射到特定类型。我想将 AGE 映射到 int,将 MENOPAUSE 映射到另一个枚举类型,将 BREAST 映射到 bool 等等。< br/>那么是否可以创建一个函数来返回一个类型的值,该值取决于 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.

最佳答案

一种惯用的方法是使用特征:

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定义为一个函数模板:

template<ATTRIBUTE A>
typename Map<A>::type map_attr() { return Map<A>::value; }

并将其用作:

auto something = map_attr<AGE>();

它遵循一个最小的工作示例:

#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++ - 将枚举值映射到 C++ 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41415265/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com