Simon Goodman Simon Goodman - 3 months ago 9
C++ Question

Specialised template return/set an enum value based on the variable type

If I have an enum defined as ...

enum MyValue
{
Unk,
A,
B
};


I want to create a specialised template that return/set the type based on the variable type itself

template<typename T>
struct get_value
{
// the 'value' should be MyValue::Unk
};

template<>
struct get_value<int>
{
// the 'value' should be MyValue::A
};

template<>
struct get_value<double>
{
// the 'value' should be MyValue::B
};


That way I could call the struct

auto x = get_value<char>::value; // == MyValue::Unk


And

auto y = get_value<int>::value; // == MyValue::A


Is that possible in c++, if so, how could it be achieved?

Answer

With the following:

template<typename T>
struct get_value
{
  static constexpr MyValue value = MyValue::Unk;
};

template<>
struct get_value<int>
{
  static constexpr MyValue value = MyValue::A;
};

template<>
struct get_value<double>
{
  static constexpr MyValue value = MyValue::B;
};

Demo