Have enum type of any tag in a class specialization

Viewed 58

How to have enum type of any tag in a class specialization?
as this works only for one ie. L enum :

enum class K 
{
   a, b, c, d, e
};
enum class L 
{
   a, c, e,
};

template<enum L>
struct J 
{
   constexpr static int N = static_cast<int>(L::e);
   int n[N] = { 7 };

   void print() 
   {
      cout << N << "\n";
   }
};

int main()
{
   J <L::e> obj;
   obj.print();
   return 0;
}

How to have it works as common such for K and any enum tag as long as it has the same e member name?

1 Answers

If you can provide one more template argument, you can pass any enums

template<typename Type, Type en>
struct J 
{
   // ...
}

and construct the object

J <K, K::e> obj;
obj.print();

(See demo online)


Also checking the passed Type using std::is_enum, you can restrict the template types passed.

Related