这里模板参数推导很有效,因为对于函数模板,后续的模板参数可以通过函数参数进行推导。在这种情况下,模板参数
U
可以从函数参数
u
推导出来。请注意,对于类模板,如您所期望的那样,在默认模板参数之后的后续模板参数必须具有默认模板参数或者是一个模板参数包。
参考链接:
§14.1/11 Template parameters
[temp.param]
If a template-parameter of a class template, variable template, or
alias template has a default template-argument, each subsequent
template-parameter shall either have a default template-argument
supplied or be a template parameter pack. If a template-parameter of a
primary class template, primary variable template, or alias template
is a template parameter pack, it shall be the last template-parameter.
A template parameter pack of a function template shall not be followed
by another template parameter unless that template parameter can be
deduced from the parameter-type-list ([dcl.fct]) of the function
template or has a default argument ([temp.deduct]). A template
parameter of a deduction guide template ([temp.deduct.guide]) that
does not have a default argument shall be deducible from the
parameter-type-list of the deduction guide template. [ Example:
template<class T1 = int, class T2> class B;
template<class... T, class... U> void f() { }
template<class... T, class U> void g() { }
— end example ]
您可以尝试使
U
不可推导,并观察会发生什么:
template <bool T=true, class U>
void f(){
if(T){ cout<<true;}
else cout<<false;
}
int main() {
f();
f<true>();
f<true, int>();
return 0;
}
请注意,您必须显式指定所有模板参数,以使代码正常工作,这使得默认模板参数完全无意义。如果您想要使
f()
或
f<true>()
正常工作,则需要为
U
也提供一个默认的模板参数(或者将其作为模板参数包) 。
template <bool T=true, class U=int>
void f(){
if(T){ cout<<true;}
else cout<<false;
}
int main() {
f();
f<false>();
f<false, char>();
return 0;
}