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};
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.
You can map the enum value to a String. This mapping is not as efficient, but you can add or remove enum values without any side effects.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.
The most common option to map an enum value to and from its database representation in JPA before 2.1 is to use the @Enumerated annotation. This way, we can instruct a JPA provider to convert an enum to its ordinal or String value.
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;
};
// ...
Then you can define map_attr
as a function template:
template<ATTRIBUTE A>
typename Map<A>::type map_attr() { return Map<A>::value; }
And use it as:
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, "!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With