Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial specialization with more template parameters

Is a partial specialization allowed to have more template parameters than the primary template? My understanding was that the a partial specialization must have either lesser or the same number of template parameters as the primary template.

I am reading C++ Templates (2nd Edition) and in that it is mentioned on Section 5.4 (Page 72) that

template <typename T, std::size_t SZ>
struct MyClass<T[SZ]>{
    static void print(){}
};

and

template <typename T, std::size_t SZ>
struct MyClass<T (&)[SZ]>{
    static void print(){}
};

are both partial specializations of the primary template

template <typename T>
struct MyClass;

The accompanying code works fine. But is this correct? Can a partial specialization have more template parameters than the primary template?

Edit - This question has been marked a duplicate of another question but the answers there are unrelated to the question here. The Question here is reagarding the number of template parameters and the comments and quick rereading of the standard clarified the answer for me.

like image 495
MSS Avatar asked Dec 13 '18 13:12

MSS


People also ask

Which template can have multiple parameters?

Explanation of the code: In the above program, the Test constructor has two arguments of generic type. The type of arguments is mentioned inside angle brackets < > while creating objects.

What is function template with multiple parameters in C++?

Multiple parameters can be used in both class and function template. Template functions can also be overloaded. We can also use nontype arguments such as built-in or derived data types as template arguments.

Why do we use template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is mean by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.


1 Answers

Yes, a partial specialisation can indeed have more template parameters than the primary template. A typical example of this use is std::function:

template <class T>
struct function;

template <class R, class... A>
struct function<R (A...)>
{
  // std::function as we know it
};
like image 122
Angew is no longer proud of SO Avatar answered Sep 29 '22 01:09

Angew is no longer proud of SO