模板函数参数包不在列表的末尾

问题描述 投票:0回答:1

以下代码无法在g ++和clang ++上使用不同的错误消息进行编译。特别是,它是触发错误的第二条主线。

我不明白为什么,因为没有什么含糊不清的。该函数有两个参数,这意味着模板包必须具有两个参数,并且所有类型都是明确指定的。

任何解释?

#include <iostream>
enum A {A1,A2};
template <typename...Ts, A a=A2>
void foo(Ts...ps) { (std::cout << ... << ps); }

int main()
{
    foo<int,int>(1,2);     // this compiles
    foo<int,int,A2>(1,2);  // this does not compile
    return 0;
}
c++11 templates c++17 function-templates
1个回答
1
投票

变量模板参数是贪婪的,因此如果您尝试为具有可变参数的模板显式指定模板参数,则一旦显式参数开始分配给可变参数包,所有剩余的参数都将分配给该包。在这种情况下,A2不是一个类型,因此当编译器尝试将其分配给Ts...包时,会导致错误。

您可以重载模板,允许将enum指定为第一个参数:

template <A a,typename...Ts >
void foo(Ts...ps) { std::cout << sizeof...(ps); }
template <typename...Ts>
void foo(Ts...ps) { foo<A2>(ps...); }

foo<int,int>(1,2);     // this compiles
foo<A2,int,int>(1,2);  // this compiles
© www.soinside.com 2019 - 2024. All rights reserved.