Variadic function template with pack expansion not in last parameter(带有包扩展的可变函数模板不在最后一个参数中)
问题描述
我想知道为什么下面的代码不能编译:
I am wondering why the following code doesn't compile:
struct S
{
template <typename... T>
S(T..., int);
};
S c{0, 0};
此代码无法同时使用 clang 和 GCC 4.8 进行编译.这是 clang 的错误:
This code fails to compile with both clang and GCC 4.8. Here is the error with clang:
test.cpp:7:3: error: no matching constructor for initialization of 'S'
S c{0, 0};
^~~~~~~
test.cpp:4:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
S(T..., int);
^
在我看来这应该可行,并且 T 应该被推导出为长度为 1 的包.
It seems to me that this should work, and T should be deduced to be a pack of length 1.
如果标准禁止做这样的事情,有谁知道为什么?
If the standards forbids doing things like this, does anyone know why?
推荐答案
因为当一个函数形参包不是最后一个形参时,那么模板形参包就不能从中推导出来,模板实参推导会忽略它.
Because when a function parameter pack is not the last parameter, then the template parameter pack cannot be deduced from it and it will be ignored by template argument deduction.
因此将两个参数 0, 0
与 , int
进行比较,结果不匹配.
So the two arguments 0, 0
are compared against , int
, yielding a mismatch.
这样的推导规则需要涵盖很多特殊情况(比如两个参数包并排出现时会发生什么).由于参数包是 C++11 中的一个新特性,相应提案的作者在起草规则时比较保守.
Deduction rules like this need to cover many special cases (like what happens when two parameter packs appear next to each other). Since parameter packs are a new feature in C++11, the authors of the respective proposal drafted the rules conservatively.
请注意,如果没有以其他方式推导出,尾随模板参数包将为空.所以当你用一个参数调用构造函数时,事情就会起作用(注意这里模板参数包和函数参数包的区别.前者是拖尾的,后者不是).
Note that a trailing template parameter pack will be empty if it is not otherwise deduced. So when you call the constructor with one argument, things will work (notice the difference of template parameter pack and function parameter pack here. The former is trailing, the latter is not).
这篇关于带有包扩展的可变函数模板不在最后一个参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有包扩展的可变函数模板不在最后一个参数中


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01