The difference between a template with two parameters and two template declarations with one parameter each

What is the difference between the following two ads:

template<class T, class functor> methodReturnType className::methodName(functor f) 

and

 template<class T> template<class functor> methodReturnType className::methodName(functor f) 

I tried to write a method that will work with an argor functor. The second declaration allowed me to avoid declaring the entire class as a template of both T and functor. I wanted to have a class class ClassName with only one T parameter, but inside this class the method had another parameter functor without declaring the whole class as a template of two parameters. It worked, but I did not quite understand it.

+6
source share
2 answers

The second option is suitable for your case according to the language rules.

n3376 14.5.2 / 1

The participant template of the class template, which is defined outside the definition of its class, must be specified using the template parameters of the class template , followed by the template parameters of the member template.

[Example:

 template<class T> struct string { template<class T2> int compare(const T2&); template<class T2> string(const string<T2>& s) { /∗ ... ∗/ } }; template<class T> template<class T2> int string<T>::compare(const T2& s) { } 

- end of example]

+3
source

The first is the (non-template) member function of the class template< typename T, typename functor > class className . The second is the template template member function template template <typename T> class className , for example:

Firstly:

 template <typename T, class Functor > class ClassName { ReturnType functionName( Functor f ); }; 

Secondly:

 template <typename T> class ClassName { template <typename Functor> ReturnType functionName( Functor f ); }; 

You say you don’t understand this, but you seem to have learned the essential: in the second case, the template class has only one parameter, but even after creating the instance (definition of type T ), the member function remains a template that can be created by several types. And since this is a function template, the template argument is a deduction, so you do not need to specify a type; the compiler will figure it out when you call the function.

+3
source

Source: https://habr.com/ru/post/948921/


All Articles