c++ - 如何使用模板创建编译时类字段?

标签 c++ variadic-templates c++17 template-meta-programming

背景和基本原理简介

我正在设计一个编译时 ECS。该设计有它的细节——例如,会有各种各样的实体。这意味着组件的总数可能相当高,而每个实体的组件数量将相当低(有一些明显的几乎无处不在的公共(public)元素,例如 SpriteBoundingBox )

我的方法

我将实现以下接口(interface):

/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;

/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?

我编写的Entity类的开始:

template <typename ...>
class Entity final {};

但是,我不知道如何为相应的组件类型创建句柄数据字段,以及是否有可能。任何人都可以帮助我或解释为什么它不起作用(或者可能建议不同的解决方案)?

最佳答案

只需使用std::tuple。注意: get 要求每个 Components... 都是不同的类型

template <typename ... Components>
class Entity final { 
    std::tuple<Components...> components;  
    template<typename Component>
    void add(Component component) // possibly cv / ref qualified
    {
        std::get<std::decay_t<Component>>(components) = component;
    }
};

关于c++ - 如何使用模板创建编译时类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47284529/

相关文章:

c++ - 将值从一个函数传递到另一个函数

c++ - 可变参数模板和参数重载不能一起工作

c++ - 如何检测构造函数是否真的是 constexpr,以便我可以使用静态初始化?

c++ - 激发 'inline' 说明符的现实世界示例?

c++ - 返回引用时的 std::vector::emplace_back 错误 (C++17)

c++ - 流缓冲区中的默认内容

c++ - 运算符重载

c++ - 遍历 RapidJson 中的数组并获取对象元素

c++ - 是否可以对参数包进行类型定义?

c++ - 可变参数模板折叠程序在 gcc9 中失败