显式指定的模板参数包 [英] Explicitly-specified template parameter packs

查看:26
本文介绍了显式指定的模板参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有以下一段代码:

Let's say, I have the following piece of code:

#include <iostream>

template <size_t... Is> struct E {};

template <typename... Ts, size_t... Is>
void func (E<Is...>, Ts...) {std::cout << __PRETTY_FUNCTION__ << std::endl;}

int main()
{
    func(E<1,2,3>{}, 1, 'a');
}

它工作得非常好并产生

void func(E<Is ...>, Ts ...) [with Ts = {int, char}; long unsigned int ...Is = {1, 2, 3}]

但是,如果我将 func 调用替换为 func(E<1,2,3>{}, 1, 'a');,会导致编译错误,即

However, if I replace func call with func<int, char, 1, 2, 3>(E<1,2,3>{}, 1, 'a');, it will cause the compilation error, i.e.,

template argument deduction/substitution failed

为什么编译器禁止显式指定多个参数包?

Why compiler forbids the explicit specification of multiple parameter packs?

推荐答案

这遵循模板参数推导的规则.

This follows from the rules for template argument deduction.

当您为 func 显式指定模板参数时,编译器会贪婪地将其匹配到第一个参数包.编译器不知道一旦您开始将 ints 放入参数中,它就应该开始替换 Is....

When you explicitly specify the template parameters for func, the compiler will match it to the first parameter pack greedily. The compiler does not figure out that once you start putting ints in the parameters, it should start substituting for Is....

相反,它将继续替换 Ts...,并且您将收到一条错误消息:

Instead, it will continue substituting for Ts..., and you'll get an error message along the lines of:

expected a type, but got 1

对于第三个明确指定的参数.

for the 3rd explicitly specified parameter.

如果您指定only Ts...,您可以看到这一点,如下所示:

You can see this if you specify only the Ts..., like this:

func<int, char>(E<1,2,3>{}, 1, 'a');

它编译得很好.

这篇关于显式指定的模板参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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