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

111 Views Asked by At

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?

2

There are 2 best solutions below

0
fdan On BEST ANSWER

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 {};
0
zhanginou On

Laying out the solution from the accepted response in case it helps others:

template <Enum ENUM_1, Enum ENUM_2 = ENUM_1>
class Test
{
public:
    Test()
    {
        std::cout << "base\n";
    }
};

template <Enum ENUM>
class Test<ENUM, ENUM>
{
public:
    Test()
    {
        std::cout << "special\n";
    }
};


int main()
{
    Test<Enum::A, Enum::B> test_AB{};
    Test<Enum::A, Enum::A> test_AA{};
    Test<Enum::A> test_A{};
}

prints out

base
special
special