1

I have a struct which takes enum class value on the template parameter.

template <typename EnumValue>
struct Type
{
public:
    static constexpr int VALUE = static_cast<int>(EnumValue);
};

enum class MyEnum {Val1, Val2};

std::cout << Type<MyEnum::Val2>::VALUE << std::endl;

I expected it to work, but it gives errors:

error: expected primary-expression before ‘)’ token
     static constexpr int VALUE = static_cast<int>(EnumValue);

error: type/value mismatch at argument 1 in template parameter list for ‘template<class EnumValue> struct Type’
  std::cout << Type<MyEnum::Val2>::VALUE << std::endl;

How to fix these errors without changing the template parameters for Type?

Since I don't want the template inputs to be changed, I don't want to use something like this:

template <typename EnumType, EnumType EnumValue>
struct Type...
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • How about creating another class template like `template Helper` and then go with `Type >`? Drops any information on from which enum it came, though, might not work out depending on what you want to achieve. – Aziuth May 04 '20 at 11:45
  • @Aziuth enum class is not implicitly convertible to int and it needs cast. – Mojtaba Shahbazi May 04 '20 at 12:03

2 Answers2

1

You can't.

typename EnumValue declares a type, it is not a value. You can't have Type<MyEnum::Val2> with an enum class in C++11.

In C++17 you will be able to write template <auto EnumValue> which does what you want.

Caleth
  • 52,200
  • 2
  • 44
  • 75
0

As @Caleth has mentioned, you need to specify the enum type and enum value to the Type struct. But as far as you do not want to change the template parameters, why not going for an static method inside Type?

template <typename EnumType>
struct Type
{
public:
   static constexpr int getValue(EnumType value)
   {
      return static_cast<int>(value);
   }
};

enum class MyEnum { Val1, Val2 };


int main()
{
   std::cout << Type<MyEnum>::getValue(MyEnum::Val2) << std::endl;
}
TonySalimi
  • 8,257
  • 4
  • 33
  • 62