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

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

问题描述

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

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天全站免登陆