我想通过“组合”类型来创建一个唯一的 id。输入类型的顺序无关紧要,输入相同的类型组合应始终返回相同的 id(在相同的运行时)。我想在实体组件系统中使用它来识别组件的组合。
一个几乎可以完成工作的想法:
class Archetype
{
public:
template <typename... Types>
static uint32_t CreateArchetype()
{
return GetArchetypeIndex<Types...>();
}
private:
template <typename... Types>
static uint32_t GetArchetypeIndex()
{
static uint32_t index = GetNewArchetypeIndex();
return index;
}
static uint32_t GetNewArchetypeIndex()
{
static uint32_t lastID = 0u;
return ++lastID;
}
};
int main()
{
std::cout << Archetype::CreateArchetype<uint16_t, uint32_t, int, bool>() << std::endl;
std::cout << Archetype::CreateArchetype<uint16_t, uint32_t, int, bool>() << std::endl;
// Same Types but different order
std::cout << Archetype::CreateArchetype<int, bool, uint16_t, uint32_t>() << std::endl;
std::cout << Archetype::CreateArchetype<int, bool, uint16_t, uint32_t>() << std::endl;
}
Output: 1, 1, 2, 2
Goal: 1, 1, 1, 1
这将返回一个唯一的 id,但它确实关心订单。也许这可以通过某种CreateArchetype()
“可变模板排序魔法”以某种方式对函数中的类型进行排序来解决,但我还没有设法做到这一点,有可能还是有其他选择?