c++templatespartial-specializationc++-loki

c++ template specialization and number of template arguments


I have just started learning templates, I was going through an example where TypeList is implemented and saw this implementation of Length method for TypeList.

template <class TList> struct Length;
template <> struct Length<NullType>
{
    enum { value = 0 };
};

template <class T, class U>
struct Length< Typelist<T, U> >
{
    enum { value = 1 + Length<U>::value };
};

my question is that primary length template has only 1 parameter (TList) but the specialization has 2 parameters. How is this possible, I read in other places that specialization to have less number of parameters


Solution

  • the first :

    template <> struct Length<NullType>
    

    is full specialization, the second:

    template <class T, class U>
    struct Length< Typelist<T, U> >
    

    is partial specialization.

    With full specialization you give the exact type on which to specialize. With partial specialization you allow all types which adheres to some restrictions, in this case its ability to create type : Typelist<T, U>, also two template type arguments must be provided.

    For more details see here:

    http://en.cppreference.com/w/cpp/language/template_specialization http://en.cppreference.com/w/cpp/language/partial_specialization

    my question is that primary length template has only 1 parameter (TList) but the specialization has 2 parameters. How is this possible,

    thats what partial specialization allow, the template parameter list must differ (for details see above link), but they must provide the same number of type arguments as primary template expects (Length< Typelist<T, U> >).