Search code examples
c++templatesenumsspecialization

Template class specialization for when the two enum values are the same


I have a Test class which is templated on two enums of the same enum type. I'm trying to write a specialization for this Test class for when the two enum values are the same.

enum class Enum
{
    A,
    B
};

template <Enum ENUM_1, Enum ENUM_2>
class Test {};

template <Enum ENUM>
class Test<ENUM, ENUM> {};

int main()
{
    Test<Enum::A> test;
}

The above results however in the following error:

main.cpp:23:5: error: too few template arguments for class template 'Test'
    Test<Enum::A> test;
    ^
main.cpp:13:7: note: template is declared here
class Test
      ^
1 error generated.

What is wrong with the above code?


Solution

  • Test requires exactly two template parameters. Specializing doesn't remove ENUM_2. If you want to instantiate Test with a single type and use it for ENUM_2 as well, you can define a default for ENUM_2:

    template <Enum ENUM_1, Enum ENUM_2 = ENUM_1>
    class Test {};