gpt4 book ai didi

c++ - 改运行时研究一个编译时间一

转载 作者:行者123 更新时间:2023-11-30 02:26:15 25 4
gpt4 key购买 nike

出于学习目的,我正在尝试使用 C++ 实现通用 ECS 库。我想了很多方法来实现,但我总是遇到问题。所以,如果你能帮我解决这个问题:

假设我有一个 constexpr hana::tuplehana::type_c组件,比如:

struct C1 {};
struct C2 {};
struct C3 {};

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);

现在我有一个组件存储类型,这在这里不是问题,所以我们称它为存储(每个组件的类型不同):

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)
);

这样我应该能够在编译时找到索引并在运行时访问正确的元素。但我是元编程方面的新手,所以我想有人可以做出更好的东西。

最佳答案

首先,不需要使用to_tuple(tuple_t<...>) ;你可以只使用 tuple_t<...> .现在,我认为您真正想要做的(因为您似乎需要运行时存储,这是有道理的)是​​:

// "map" of a set of types to a storage of some type
using StorageMap = hana::tuple<
hana::pair<hana::tuple<hana::type<C1>, hana::type<C2>>, StorageA>,
hana::pair<hana::tuple<hana::type<C3>>, StorageB>
>;
// Actual object that contains the runtime storage (and the free mapping between types)
StorageMap map;

现在,您可以实现您的 getStorage<Component>()像这样的功能:

template <typename Component>
decltype(auto) getStorage() {
auto found = index_if(map, [](auto const& pair) {
return hana::contains(hana::first(pair), hana::type<Component>{});
});
return hana::second(hana::at(map, found));
}

哪里index_if是所提供函数的一个简单变体 in this answer这将适用于任意谓词而不是特定元素。当我有空闲时间时,此功能将添加到 Hana(请参阅 related ticket)。

关于c++ - 改运行时研究一个编译时间一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com