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节中讨论。
原文链接: https://www.cnblogs.com/5iedu/p/12709810.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/392632
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!