c++ - 明确指定的模板参数包

标签 c++ variadic-templates template-argument-deduction

假设我有以下代码:

#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<int, char, 1, 2, 3>(E<1,2,3>{}, 1, 'a');,则会导致编译错误,即
template argument deduction/substitution failed

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

最佳答案

这遵循模板自变量推导的规则。

当您显式指定func的模板参数时,编译器会贪婪地将其匹配到第一个参数包。编译器无法确定一旦将int放入参数中,它就应该开始替换Is...

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

expected a type, but got 1

用于第三个明确指定的参数。

如果仅指定Ts...,则可以看到以下内容:
func<int, char>(E<1,2,3>{}, 1, 'a');

编译就好了。

关于c++ - 明确指定的模板参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62305390/

相关文章:

c++ - 你能 'redeclare' 一个子类中的变量吗?

c++ - 计算数组中的反转次数

c++ - 使用 C++11 可变参数模板在编译时快速排序

c++ - 为什么编译器不能在与转换运算符一起使用时推导出模板参数?

c++ - std::basic_string 作为函数模板的参数不能从 const char* 推导出

c++ - 错误 : enum is not e member of the class

c++ - VS2008 SP1 中的 Lambda 表达式支持

c++ - 无法从 'auto' 推断出 'tuple_cat'

c++ - 在可变参数模板中使用垫片的更简洁的方法?

c++ - 为什么 C++17 标准没有带来部分类模板参数推导?