Home > Software design >  convert enum class too std::tuple
convert enum class too std::tuple

Time:11-02

I would like to be able to create a std::tuple based on the enum value passed as a template argument, if possible without using global variables.

#include <tuple>

enum class Type
{
  eInt,
  eFloat,
  eDouble
};

template <Type... type>
class Test
{
public:

private:
  std::tuple < ? > m_data;
};

int main()
{
  Test<Type::eDouble, Type::eInt> t1;  // m_data = std::tuple<double, int>
  Test<Type::eInt, Type::eFloat> t2; // m_data = std::tuple<int, float>
}

CodePudding user response:

Step one, figure out how to convert one constant to a type:

template <Type> struct MakeType {};
template <> struct MakeType<Type::eInt> {using type = int;};
template <> struct MakeType<Type::eFloat> {using type = float;};
// ...

This lets you do e.g. MakeType<Type::eInt>::type to get an int.

Now you can do std::tuple<typename Maketype<T>::type...> (where T is the template parameter pack, renamed from type for clarity).

  •  Tags:  
  • c
  • Related