使用模板化基类型对派生结构进行struct初始化

use*_*989 0 c++ c++11

我试图在派生自模板结构上使用struct初始化.代码如下:

template <class Derived>
struct Event{
//the level of access on the ctor has nothing to do with the problem
//protected:
//    Event() = default;
};

struct MoveEvent: Event<MoveEvent>{
    int x, y;
};


int main(){
    //how do I make this work?
  //MoveEvent event = {.x =5, .y = 4};
}
Run Code Online (Sandbox Code Playgroud)

我认为这可能是与CTRP,但改变Event<MoveEvent>Event<int>产生同样的问题.此外,我认为这是与POD的问题,而是std::is_pod返回trueMoveEvent.那么这里的问题是什么?为什么我不能使用struct初始化?

Bar*_*rry 5

您只能对聚合进行聚合初始化.汇总来自[dcl.init.aggr]:

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

MoveEvent不是聚合.因此,您将不得不添加一个构造函数:

template <class Derived>
struct Event {
};

struct MoveEvent: Event<MoveEvent> {
    MoveEvent(int x, int y) : x(x), y(y) { }
    int x, y;
};


int main() {
    MoveEvent event{5, 4}; // NOW this is fine
}
Run Code Online (Sandbox Code Playgroud)