[英]Aggregate initialization in C++
I have a base class Event, from which concrete events derive:我有一个基类 Event,从中派生出具体的事件:
struct Event
{
};
struct CollisionEvent : Event
{
//CollisionEvent(Entity entityA, Entity entityB) : entityA(entityA), entityB(entityB) {}
Entity entityA;
Entity entityB;
};
this class is a POD, and I should be able to perform aggregate initializaion.这个类是一个 POD,我应该能够执行聚合初始化。 But the following code fails to compile:
但以下代码无法编译:
called from application:
eventBus->DispatchEvent<CollisionEvent>(mEntities[i], mEntities[j]);
in EventBus.h:
template <typename TEvent, typename... Args>
void DispatchEvent(Args&&... args)
{
auto it = mEventHandlers.find(typeid(TEvent));
if (it != mEventHandlers.end())
for (auto &&eventHandler : it->second)
eventHandler->Invoke(TEvent{ std::forward<Args>(args)... });
}
saying that it cannot convert initializer list to TEvent.说它不能将初始化列表转换为 TEvent。 Why?
为什么?
For aggregate initialization you need to initialize the base class, even if it's empty.对于聚合初始化,您需要初始化基类,即使它是空的。
eventBus->DispatchEvent<CollisionEvent>(Event{}, mEntities[i], mEntities[j]);
There were also some changes regarding what is and what isn't an aggregate in recent standards - until C++17 a class having a base class can't be aggregate-initialized, so you can't make it work in C++14.在最近的标准中,关于什么是聚合和什么不是聚合也有一些变化——直到 C++17,一个具有基类的类不能被聚合初始化,所以你不能让它在 C++ 中工作14. (see https://godbolt.org/z/Pq5PfecKq )
(见https://godbolt.org/z/Pq5PfecKq )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.