2

Having the following code

enum class EClass { A, B, C, D, E };

template <typename T> struct S;

template <> struct S<EClass::A> {
  static constexpr std::string_view name = "A";
}

I get the following error:

error: template argument for template type parameter must be a type
template <> struct S<EClass::A> {

What is wrong with the A member of Eclass? shouldn't it be a type? I'm using c++ 20

2 Answers2

3

No. EClass is a type, EClass::A is a value of type EClass, not a type.

You could define your template as template <EClass T> struct S;, then it would work (but only admit values of type EClass as template parameters).

Cubic
  • 14,902
  • 5
  • 47
  • 92
3

The problem here is that EClass::A is not a type; it's a value of type EClass. Enum values in C++ are not treated as types, so you can't specialize a template based on them directly.

If you want to map enum values to corresponding names, you can take a different approach, such as using a function or a variable template instead of a class template specialization.

Here's an example using a constexpr function:

enum class EClass { A, B, C, D, E };

constexpr std::string_view getName(EClass e) {
  switch (e) {
    case EClass::A: return "A";
    case EClass::B: return "B";
    case EClass::C: return "C";
    case EClass::D: return "D";
    case EClass::E: return "E";
  }
  return ""; // or throw an exception, or handle it some other way
}

Alternatively, you can also use a variable template specialization:

enum class EClass { A, B, C, D, E };

template <EClass e> struct S;

template <> struct S<EClass::A> {
  static constexpr std::string_view name = "A";
};

// More specializations...

Here, the template parameter e is a non-type template parameter, and it's specialized based on the value EClass::A, which is allowed.

NoName
  • 643
  • 3
  • 8