为什么参数后面的模板类参数有默认值,但在variadic之前也必须有默认值? Live example
template<class A = int, class B, class ...Args> // B must have default argument
struct Dat{};
另一方面,如果A
没有默认参数,那么ok:
template<class A, class B, class ...Args> // B must have default argument
struct Dat{};
答案 0 :(得分:6)
这与可变参数模板无关:
template<class First, class Second> struct X {};
X<int, double> // instantiates X with First == int, Second == double
参数int
和double
用于从左到右填充参数First
,Second
。第一个参数指定第一个参数,第二个参数指定第二个参数。当参数具有默认值时,您无需指定参数:
template<class First, class Second = double> struct X {};
X<int> // instantiates X with First == int, Second == double
如果您现在有一个没有默认参数的第三个参数,则无法使用默认参数:
template<class First, class Second = double, class Third> struct X {};
X<int, char> // tries to instantiate X with First == int, Second == char,
// Third == ??
模板参数包可以为空,因此它可以使用带有默认参数的参数:
template<class First, class Second = double, class... Pack> struct X {};
X<int> // instantiates X with First == int, Second == double, Pack == (empty)
X<int, char> // First == int, Second == char, Pack == (empty)
X<int, char, short, bool> // First == int, Second == char, Pack == {short, bool}
在OP的例子中:
template<class A = int, class B, class ...Args> struct Dat {};
^~~~~~~ ^~~~~~~ ^~~~~~~~~~~~~
| | |no argument required
| |an argument IS required
|no argument required
因此,您必须为第二个参数提供参数,因此,您还需要为 first 参数提供参数。不能使用第一个参数的默认参数。