默认模板参数是否可以以不从右开始的方式使用“默认值”?
标准是什么?
编译器将如何解释?
例如,此代码有效 令我感到非常惊讶。
#include <iostream>
using namespace std;
template <bool T=true, class U> //"default" from LEFT-most parameter
void f(U u){
if(T){ cout<<true;}
else cout<<false;
}
int main() {
auto x = []( ){ };
f(x);
return 0;
}
在此处查看现场演示:https://ideone.com/l6d9du
最佳答案
模板参数推导在这里很有效,因为对于函数模板,后续的模板参数可能由函数参数推导。在这种情况下,模板参数 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; // error // U can be neither deduced from the parameter-type-list nor specified template<class... T, class... U> void f() { } // error template<class... T, class U> void g() { } // error
— end example ]
你可以尝试制作 U
undeducible,看看会发生什么:
template <bool T=true, class U> //"default" from LEFT-most parameter
void f(){
if(T){ cout<<true;}
else cout<<false;
}
int main() {
f(); // Fail. Can't deduce U.
f<true>(); // Fail. Can't deduce U.
f<true, int>(); // Fine. T=true, U=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(); // Fine. T=true, U=int
f<false>(); // Fine. T=false, U=int
f<false, char>(); // Fine. T=false, U=char
return 0;
}
关于c++ - 默认模板参数 - 不必来自对吗?为什么有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137281/