如何在可变参数类模板中获取类型的索引? [英] How can I get the index of a type in a variadic class template?
问题描述
我有一个可变参数引擎模板类:
I have a variadic Engine template class:
template <typename ... Components> class Engine;
我想在编译时为每个组件分配一个编号,该编号等于它们的顺序。进行以下调用时将返回此值:
I'd like to assign a number to each component at compile time which is equivalent to their ordering. This would be returned when making the following call:
template <typename Component> int ordinal();
例如,如果:
Engine<PositionComponent, PhysicsComponent, InputComponent> engine;
已声明,调用:
engine.ordinal<PhysicsComponent>();
将返回1,使用InputComponent而不是PhysicsComponent的类似调用将返回2。
would return 1 and a similar call with InputComponent instead of PhysicsComponent would return 2.
有可能吗,如果可以,人们会怎么做?
Is it possible, and if yes, how would one go about it?
推荐答案
因此,您想在<$中找到 Component
的索引c $ c>组件... ?
So you want to find the index of Component
in Components...
?
template <typename... >
struct index;
// found it
template <typename T, typename... R>
struct index<T, T, R...>
: std::integral_constant<size_t, 0>
{ };
// still looking
template <typename T, typename F, typename... R>
struct index<T, F, R...>
: std::integral_constant<size_t, 1 + index<T,R...>::value>
{ };
用法:
template <typename Component>
size_t ordinal() { return index<Component, Components...>::value; }
按构造,试图获取普通不在
Components ...
中的 Component
将是编译错误。似乎合适。
As constructed, trying to get the ordinal
of a Component
not in Components...
will be a compile error. Which seems appropriate.
这篇关于如何在可变参数类模板中获取类型的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!