功能模板参数包不在参数列表的结尾 [英] Function template parameter pack not at the end of the parameter list
问题描述
以下代码编译并运行确定。
The following code compiles and runs ok.
void foo() {
}
template <typename T, typename... Args>
void foo(T x, Args... args) {
cout << x << endl;
foo(args...);
}
// inside main()
foo(1,1,1);
此其他代码不能编译:
void foo() {
}
template <typename... Args, typename T>
void foo(Args... args, T x) {
foo(args...);
cout << x << endl;
}
// inside main()
foo(1,1,1);
编译器说没有匹配的函数调用 foo ,1,1)
,并说 foo(Args ... args,T x)
是候选者,但模板参数推导/ ,因为候选人期望有1个参数,但提供了3个。
The compiler says that there is no matching function for call to foo(1,1,1)
and says that foo(Args... args, T x)
is a candidate, but template argument deduction/substitution failed, because candidate expects 1 argument, but 3 were provided.
这种情况下是否有任何歧义,没有编译器可以处理?这个编译错误对我来说似乎不合逻辑。也许这不符合C ++标准的目的?
Is there any ambiguity with this situation that no compiler can handle? This compile error just seems illogical to me. Maybe this is not in accordance, on purpose, with the C++ standard?
推荐答案
main.cpp:11:6: note: candidate template ignored: couldn't infer template argument 'T'
void foo(Args... args, T x) {
^
问题是参数包 Args ...
之前发生到 T
。
The problem is that the parameter pack Args...
occurs prior to T
.
Args ...
是greedy,因此没有参数被编译器推导出 T
,因此失败。
Args...
is "greedy" and so no parameters are left for the compiler to deduce T
, hence it fails.
引用标准(强调我的):
Quoting the standard (emphasis mine):
[temp.param] / 11 / p>
[temp.param]/11
函数模板的模板参数包不应遵循
另一个模板参数除非模板参数可以从函数模板的参数类型列表中推导出
,或者具有
默认参数。 [示例:
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 of the function template or has a default argument. [Example:
...
// 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
- 结束示例]
这篇关于功能模板参数包不在参数列表的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!