为什么模板类参数在带有默认值的参数之后,但在可变参数之前也必须有默认值? Live example
template<class A = int, class B, class ...Args> // B must have default argument
struct Dat{};
另一方面,如果 A
没有默认参数,一切正常:
template<class A, class B, class ...Args> // B must have default argument
struct Dat{};
最佳答案
这与可变参数模板无关:
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
因此您始终必须为第二个参数提供一个参数,因此,您也需要为第一个 参数提供一个参数。不能使用第一个参数的默认参数。
关于可变参数包之前的 C++11 默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24757588/