浅墨浓香

想要天亮进城,就得天黑赶路。

导航

第2章 类模板:2.10 模板化聚合

Posted on 2020-04-16 00:36  浅墨浓香  阅读(276)  评论(0编辑  收藏  举报

2.10 Templatized Aggregates

2.10 模板化聚合类

Aggregate classes (classes/structs with no user-provided, explicit, or inherited constructors, no private or protected nonstatic data members, no virtual functions, and no virtual, private, or protected base classes) can also be templates. For example:

聚合类(满足以下条件的类/结构体:无用户自定义的、explicit或者继承的构造函数;无私有或受保护的非静态数据成员;无虚函数;无虚的、private或protected继承的基类)也可以是模板,例如:

template<typename T>
struct ValueWithComment {
    T value;
    std::string comment;
};

defines an aggregate parameterized for the type of the value  it holds. You can declare objects as for any other class template and still use it as aggregate:

定义一个参数化value类型的聚合类。你可以像其他任何类模板一样声明聚合类对象,并且该对象仍是聚合类型的。

ValueWithComment< int> vc;
vc.value = 42;
vc.comment = "initial value";

Since C++17, you can even define deduction guides for aggregate class templates:

从C++17开始,你甚至可以聚合类模板定义为“推导向导”

ValueWithComment(char const*, char const*)-> ValueWithComment<std::string>;
ValueWithComment vc2 = {"hello", "initial value"};

Without the deduction guide, the initialization would not be possible, because ValueWithComment has no constructor to perform the deduction against.

如果没有“推导向导”,则无法进行初始化。因为ValueWithComment没有对应的可执行推导的构造函数。

The standard library class std::array<> is also an aggregate, parameterized for both the element type and the size. The C++17 standard library also defines a deduction guide for it, which we discuss in Section 4.4.4 on page 64.

标准库中的std::array<>也是一个聚合类,其元素类型和大小都是参数化的。C++17标准库还为它定义了一个推导向导,关于这一点我们将在第64页的4.4.4节中讨论。