BЈовић
BЈовић

Reputation: 64223

It is allowed to switch template arguments in a template specialization?

This answer forward declare template class Memo one way, and implemented it's partial specialization in another way.

So, the forward declaration is :

template <template <typename...> class Container, typename...> struct Memo;

and the partial specialization this :

template <typename R, typename... Args, template <typename...> class Container>
struct Memo<Container, R, std::tuple<Args...>>

The Container template argument is switched with the variadic template argument (hopefully someone understood what I just wrote). The R is just the first element in the pack.

The code compiles fine, so I guess there should be a simple explanation of why it is allowed to do.

So, why is it allowed to switch template arguments in a template specialization? Is it because a template specialization is an independent type?

Upvotes: 0

Views: 228

Answers (1)

Manu343726
Manu343726

Reputation: 14174

The order of the template argumments in a partial template specialization doesn't matter at all. Thats because a partial template specialization is not really a template, its only an specialization of an existing template.
That means the set of template parameters of a partial template specialization are not the parameters of a template, are only the declaration of the set of generic parameters which the specialization uses/needs.

Consider an example:

// A typelist template:
template<typename... Ts>
struct type_list {};

// A metafunction for concatenating typelists (Forward declaration):
template<typename LIST1 , typename LIST2>
struct concat;

//The partial specialization of that template for typelists:
template<typename... Ts , typename... Us>
struct concat<type_list<Ts...> , type_list<Us...>>
{
    using result = type_list<Ts...,Us...>;
};

In the partial specialization of the concat metafunction, what we are doing is to specialize the template for two unspecified typelists. So the template parameters of the typelits are unspecified, that is, are generic. And we need to "declare" that generic parameters before using it.
Consider the template parameters of a partial template specialization only as declarations of the generic paraeters which the specialization needs. Because there are not real template parameters, they don't have the restrictions of template parameters: Note that in the specialization I have used two variadic packs, which is not allowed in a template.

Upvotes: 0

Related Questions