可以将函数默认模板参数放在非默认模板参数之前吗? [英] Can function default template parameter be put before non-default ones?
问题描述
下面的代码在gcc-4.7.1上编译:
struct X {};
template< class T = X,typename U>
void f(const U& m){
}
int main(){
f&
}
但是,这不会:
结构X {};
template< class T = X,typename U>
void f(const U& m){
auto g = [](){};
}
int main(){
f<>(0);
}
gcc-4.7.1抱怨:
c.cpp:在函数'void f(const U&)':
c.cpp:5:15:error:所以我的问题是:在函数模板中将默认参数放在非默认参数之前是正确的吗?如果是,为什么第二个不编译?如果没有,为什么第一个编译? C ++ 11标准怎么说这个语法?解决方案它明确禁止类和别名。 n3290§14.1.11说明:
如果类模板或别名模板的模板参数具有默认模板参数,
template-parameter要么提供默认的模板参数,要么是模板参数
pack
函数的唯一限制似乎与参数包相关:
函数模板的模板参数包不应该是
由另一个模板参数,除非该模板参数可以推导或具有默认
参数
但是显然不涉及
鉴于第14段中没有任何内容禁止它用于函数,似乎我们必须假设它是允许的。
工作组报告中的注释似乎证实了这是意图。该部分的原始建议措辞是:
如果类模板的模板参数具有默认模板参数,则所有后续模板参数应该提供一个默认的模板参数。 [注意:这不是函数模板的要求,因为可能会推导出模板参数(14.8.2 [temp.deduct])。]
虽然我不能看到那张纸在最后的版本中的位置。
The following piece of code does compile on gcc-4.7.1:
struct X {};
template <class T = X, typename U>
void f(const U& m) {
}
int main() {
f<>(0);
}
However, this one doesn't:
struct X {};
template <class T = X, typename U>
void f(const U& m) {
auto g = [] () {};
}
int main() {
f<>(0);
}
gcc-4.7.1 complains:
c.cpp: In function 'void f(const U&)':
c.cpp:5:15: error: no default argument for 'U'
So my question is: is putting default parameters before non-default parameters correct in function template? If yes, why doesn't the second one compile? If no, why does the first one compile? How does C++11 standard say about this syntax?
解决方案 It is explicitly forbidden for classes and aliases. n3290 § 14.1.11 states:
If a template-parameter of a class 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
For functions the only restriction seems to be related to parameter packs:
A template parameter pack of a function template shall not be
followed by another template parameter unless that template parameter can be deduced or has a default
argument
But clearly that doesn't concern this case.
Given that nothing in § 14 forbids it for functions it seems we have to assume it is permitted.
A note from a working group reports seems to confirm that this is the intention. The original proposed wording of that section is:
If a template-parameter of a class template has a default template-argument, all subsequent template-parameters shall have a default template-argument supplied. [Note: This is not a requirement for function templates because template arguments might be deduced (14.8.2 [temp.deduct]).]
I can't see where that note went in the final version though.
这篇关于可以将函数默认模板参数放在非默认模板参数之前吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!