lurscher
lurscher

Reputation: 26963

ways to query template specializations at run-time / avoiding the big switch

I have a enum type:

enum class MyEnumType { A , B , C };

and i want to map these enums to description attributes; i like this approach a lot:

template <typename T>
struct MyEnumTypeDescription
{
 inline const char* get() { static_assert("description not implemented for this type"); };
};

template<>
const char* MyEnumTypeDescription<MyEnumType::A>::get() { return "A"; }

template<>
const char* MyEnumTypeDescription<MyEnumType::B>::get() { return "B"; }

....

a bit verbose but not that bad, right?

Now, the part that is cumbersome is when i want to get a description from a enumerator at run-time, it means i need to create a big-switch function

const char* getDescriptionFromEnumerator( MyEnumType t ) 
{
   case MyEnumType::A:
       return MyEnumTypeDescription<MyEnumType::A>::get();
   .....
}

is there some metaprogramming (template or macro) magic that would help me avoid all this boilerplate and error-prone coding?

Upvotes: 1

Views: 130

Answers (1)

iammilind
iammilind

Reputation: 70030

I would suggest to map it to an array:

enum MyEnumType { A , B , C };
const char *pEnumDescription[] = { "A", "B", "C" };

And based on index you can get the type at runtime.

const char* getDescriptionFromEnumerator(MyEnumType t) 
{
  return pEnumDescription[t];  // just one statement instead of switch/case
}

Upvotes: 1

Related Questions