假设,我有以下一段代码:
#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
调用,
template argument deduction/substitution failed
为什么编译器禁止多参数包的显式规范?
这遵循模板参数推导的规则。
当您显式指定func
的模板参数时,编译器会贪婪地将其与第一个参数包匹配。 编译器不知道一旦您开始在参数中放入int
s,它就应该开始替换is.。。
。
相反,它将继续替换ts...
,您将得到一条错误消息,内容如下:
expected a type, but got 1
对于第3个显式指定的参数。
如果只指定ts...
,则可以看到这一点,如下所示:
func<int, char>(E<1,2,3>{}, 1, 'a');
编译得很好。