0

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402

2 Answers2

1

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • @BrogrammerDude It works fine [here](http://coliru.stacked-crooked.com/a/cec9655d639f8fb2) – NathanOliver Mar 05 '19 at 21:30
  • if I were to implement member functions do I need to do anything fancy besides including the template parameter list above the member function in a separate .cpp file? – BrogrammerDude Mar 05 '19 at 21:30
  • @BrogrammerDude [You should not put the template in a cpp file](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). For all of the out of line member definitions you would nee something like `template return_type Vector::function_name(parameters) {}` – NathanOliver Mar 05 '19 at 21:32
0

A partial specialization for YES would look like:

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

The meaning of partial specialization is that you provide different template arguments than the base template and fill in the missing template parameters of the base template yourself.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23