为继承的Pod进行括号初始化 [英] brace initialization for inherited pod

查看:82
本文介绍了为继承的Pod进行括号初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <type_traits>


struct base_pod_t {
    unsigned x;
};

struct der_pod_t : public base_pod_t { };

int main()
{
    std::cout << "base_pod_t is POD: " << std::is_pod<base_pod_t>::value << std::endl;
    std::cout << "der_pod_t  is POD: " << std::is_pod<der_pod_t>::value << std::endl;
    base_pod_t b1 = {};     // OK
    base_pod_t b2 = {3};    // OK

    der_pod_t p1 = {};      // OK
//    der_pod_t p2 = {4};   // ERROR!
}

最后一行错误。我该如何用值来初始化 der_pod_t

Last line results in error. How can I brace initialize der_pod_t with value?

即使它是一个POD,它也会尝试使用构造函数?

It seems that even though it's a POD it tries to use constructor?

编辑:
由于@Praetorian和@dyb认为这是一个POD因此 std :: is_pod< der_pod_t> :: value 结果是正确的。

推荐答案

base_pod_t 是一个聚合,您可以对其进行初始化正在执行的是聚合初始化。

base_pod_t is an aggregate and the initialization you're performing is aggregate initialization.

来自§8.5.1[dcl.init.aggr]


1 aggregate 是一个数组或一个类(第9条),没有用户提供的构造函数(12.1),没有私有或受保护的非静态数据成员(第11章),没有基类(第10章)和虚拟函数(10.3)。

1 An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

2 按照8.5.4中的指定,由初始化程序列表初始化后,初始化程序列表中的元素将按递增的下标或成员顺序作为聚合成员的初始化程序。每个成员都从相应的 initializer-clause 中进行复制初始化。 ...

2 When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause. ...

但是, der_pod_t 不是聚合,因为它有一个基类。这是一个POD,并且列表初始化的相同规则不适用。现在,当编译器看到一个非空的 braised-init-list 时,它将首先搜索一个采用 initializer_list 的构造函数。如果未找到,则尝试匹配该类的其他构造函数。由于 der_pod_t 没有使用单个 int 作为参数的构造函数,因此会发生错误。

However, der_pod_t is not an aggregate because it has a base class. It's a POD, and the same rules for list initialization do not apply. Now, when the compiler sees a non-empty braced-init-list it'll first search for a constructor that takes an initializer_list. If none are found it then attempts to match other constructors of the class. Since der_pod_t has no constructors that take a single int as argument, the error occurs.

这篇关于为继承的Pod进行括号初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆