使用模板参数包初始化联合

时间:2020-05-11 11:03:02

标签: c++ templates entity-component-system data-oriented-design parameter-pack

我正在使用ECS和面向数据的模型编写引擎。我正在尝试避免继承和动态调度,以免每次调用update()都会破坏缓存。我想到的是这样的:

struct transformComponent {
    const unsigned short id;
    vecShort p;

    transformComponent(unsigned short id, short x, short y): p(x, y), id(id) {}
    transformComponent(unsigned short id): p(0, 0), id(id) {}
};

struct physicsComponent {
    const unsigned short id;
    unsigned short mass;
    double invmass;
    vecShort v, a, f;

    physicsComponent(unsigned short id, unsigned short mass):
        id(id), mass(mass), invmass(1/mass) {}
    physicsComponent(unsigned short id): id(id) {}
};

//...

struct component {
    enum compType {transform, physics, behavior, collision, rendering};

    union {
        transformComponent  tra;
        physicsComponent    phy;
        //...
    };

    template<typename ...argtypes>
    component(compType type, unsigned short id, argtypes... args) {
        switch(type) {
            case transform:
                tra(id, std::forward<argtypes>(args)...);
                break;
            case physics:
                phy(id, std::forward<argtypes>(args)...);
                break;
            //...
        }
    }
};

然后我有一个room类(管理器),它通过内存池保存所有系统和组件。问题是

template<typename ...argtypes>
    component(compType type, unsigned short id, argtypes... args) {
        switch(type) {
            case transform:
                tra(id, std::forward<argtypes>(args)...);
                break;

部分,编译器抱怨:

src\inc/components.h: In instantiation of 'component::component(component::compType, short unsigned 
int, argtypes ...) [with argtypes = {}]':
src\inc/components.h:94:71:   required from here
src\inc/components.h:57:5: error: no match for call to '(transformComponent) (short unsigned int&)'
   57 |     tra(id, std::forward<argtypes>(args)...);
      |     ^~~

我试图移动椭圆,但没有任何效果。我本质上想做的是避免在每个帧上同时使用模板和动态调度,但是我需要用于初始化的模板。我的基本语法错误吗?我完全错过了什么吗?我是面向数据范式的新手,所以我很乐意接受任何建议。 最小的可重现示例:https://godbolt.org/z/zGAfXS

0 个答案:

没有答案