Search code examples
c++templatespartial-specialization

C++ Partial Template Specialization:Undeclared identifier error


The goal of writing this code was to get a better understanding of partial template specialization. I'm trying to partial specialize the class Vector with three different bools.

I have an enum(for my bool) defined as:

enum MY_BOOL
{
   YES,
   NO,
   MAYBE
};

For my primary template class I have

template<class A,MY_BOOL,class B>
class Vector{};

And the partial specialization class I have is

template<MY_BOOL b>
class Vector<A,YES,B>{};

The compiler is complaining that A and B are undeclared identifiers and that the partial specialized Vector has too few arguments. Doesn't complain about 'YES' This confuses me because A and B were already defined in the primary template class. I shouldn't need to put them back in the parameter list of the partial specialized class because the point of that parameter list is to only have the variables that I want specialized.


Solution

  • In

    template<MY_BOOL b>
    class Vector<A,YES,B>{};
    

    Since A and B aren't specified, you get a compiler error. It is not going to use the A and B from the primary template, it will only use the types/value defined in the specialization.

    Since you want a specialization for each of the enum values you can do that like

    template<class A,MY_BOOL,class B>
    class Vector {};
    
    template<class A, class B>
    class Vector<A, YES, B>{ /* YES stuff */ };
    
    template<class A, class B>
    class Vector<A, NO, B>{ /* NO stuff */ };
    
    template<class A, class B>
    class Vector<A, MAYBE, B>{ /* MAYBE stuff */ };
    

    And now you have a specialization for each of the enumerations.