可变参数包之前的 C++11 默认模板参数

标签 c++ templates c++11 variadic-templates

为什么模板类参数在带有默认值的参数之后,但在可变参数之前也必须有默认值? 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

参数intdouble用于从左到右填充参数FirstSecond。第一个参数指定第一个参数,第二个参数指定第二个参数。当参数有默认值时,不需要指定参数:

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/

相关文章:

java - 如何通过JNI将java CharSequence转换为c++ char*

c++ - 可选模板参数

c++ - C++11 中的新语法 "= default"

c++ - OpenCV 图像处理——C++ vs C vs Python

c++ - std c++ 容器元素销毁和插入行为

c# - 将按钮可见性绑定(bind)到表达式 (C#)

c++ - 如何在 Visual Studio 2017 中支持 Variadic 模板类型

c++ - 使用 "constexpr"将字符串文字用于模板参数

c++ - 枚举类可以嵌套吗?

c++ - 为什么 bool 在 C++ 中不被视为 boost::true_type?