带有包扩展的可变函数模板不在最后一个参数中 [英] Variadic function template with pack expansion not in last parameter

查看:31
本文介绍了带有包扩展的可变函数模板不在最后一个参数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面的代码不能编译:

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).

这篇关于带有包扩展的可变函数模板不在最后一个参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆