【发布时间】:2017-03-29 09:29:56
【问题描述】:
我正在尝试在 C++ 中实现一个通用 ECS 库以用于学习目的。我想了很多方法来实现,但我总是遇到问题。所以如果你能帮我解决这个问题:
假设我有一个 constexpr hana::tuple 的 hana::type_c 组件,类似于:
struct C1 {};
struct C2 {};
struct C3 {};
constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
现在我有了一个组件存储类型,这里不成问题,所以我们称之为Storage(每个组件的类型不同):
struct Storage {};
我想用Storage 类型链接每个组件或每个组件组。所以最简单的方法就是这样做:
constexpr auto component_storage = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1, C2>), type_c<Storage>),
hana::make_pair(hana::to_tuple(hana::tuple_t<C3>), type_c<Storage>)
);
但现在的问题是运行时。如果我初始化该元组但使用真正的存储而不是type_c<Storage>,我将不得不遍历元组以找到我需要的Storage。所有这些都在运行时没有?
这真的很糟糕,我的上一个版本有 Component::getStorage() 之类的东西,而且它是免费的(但更具限制性)。
所以问题是:我怎样才能拥有一些 getStorage<Component>() 函数,它在运行时不会花费任何成本? 我的意思是什么都没有,我的意思是只返回存储的引用。
编辑:到目前为止我认为的唯一方法非常简单(听起来不错)。
伪代码
struct LinkedStorage {
hana::tuple<...> storages;
hana::tuple<hana::pair...> index;
};
至少是这样的:
constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
constexpr auto storage = hana::to_tuple(hana::tuple_t<Storage, Storage>);
constexpr auto index = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1>, 0),
hana::make_pair(hana::to_tuple(hana::tuple_t<C2, C3>, 1)
);
就像我应该能够在编译时找到索引并在运行时访问正确的元素。但我是元编程新手,所以我想有人可以做得更好。
【问题讨论】:
标签: c++ metaprogramming boost-hana