具有两个参数的模板与两个模板的两个声明之间的差异,每个模板具有一个参数

Hél*_*ène 6 c++ templates

接下来的两个声明之间有什么区别:

template<class T, class functor>
methodReturnType className::methodName(functor f)
Run Code Online (Sandbox Code Playgroud)

和:

template<class T>
template<class functor>
methodReturnType className::methodName(functor f)
Run Code Online (Sandbox Code Playgroud)

I was trying to write a method that would work with a functor arg. The second declaration allowed me to avoid to declare the whole class as a template of both T and functor. I wanted to have a template class className of only one parameter T, but inside that class, a method had another parameter functor, while not declaring the whole class as a template of two parameters. It worked, but I didn't thoroughly understand it.

For*_*veR 3

根据语言规则,第二种变体适合您的情况。

\n\n

n3376 14.5.2/1

\n\n

在类模板定义之外定义的类模板的成员模板应使用类模板的模板参数后跟成员模板的模板参数来指定。

\n\n

[ 例子:

\n\n
template<class T> struct string {\ntemplate<class T2> int compare(const T2&);\ntemplate<class T2> string(const string<T2>& s) { /\xe2\x88\x97 ... \xe2\x88\x97/ }\n};\ntemplate<class T> template<class T2> int string<T>::compare(const T2& s) {\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

\xe2\x80\x94 结束示例]

\n