启用默认初始化列表构造函数

Enable default initializer list constructor

我相信现代 C++ 初始化列表对于初始化对象非常有用,以至于无需定义自己的构造函数:

struct point
{
    float coord[3];
};

point p = {1.f, 2.f, 3.f}; // nice !

但是,当我的 class 继承自另一个 class 时,这不起作用:

template<typename T>
class serializable
{
    protected:
        serializable() = default;
    ...
    // other stuff
}

struct point : public serializable<point>
{
    float coord[3];
};
point p = {1.f, 2.f, 3.f}; // Doesn't work :(

我尝试将 point() = default; 添加到我的观点 class,但这也没有用。我怎样才能用初始化列表初始化点?

您的原始案例依赖于聚合初始化 [dcl.init.list]:

List-initialization of an object or reference of type T is defined as follows:
...
— Otherwise, if T is an aggregate, aggregate initialization is performed

聚合和聚合初始化来自[dcl.init.aggr],强调我的:

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).

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.

但是现在,由于point有基数class(serializable<point>),point不再是聚合,不再支持聚合初始化。

解决办法就是简单的提供这样一个构造函数来初始化point:

struct point : public serializable<point>
{
    template <typename... T>
    point(T... ts) 
    : coord{ts...}
    { } 

    float coord[3];
};