如何在可变参数类模板中获取类型的索引?

Nic*_*ert 5 c++ variadic-templates c++11

我有一个可变的Engine模板类:

template <typename ... Components> class Engine;
Run Code Online (Sandbox Code Playgroud)

我想在编译时为每个组件分配一个数字,这相当于它们的排序.拨打以下电话时会返回此信息:

template <typename Component> int ordinal();
Run Code Online (Sandbox Code Playgroud)

例如,如果:

Engine<PositionComponent, PhysicsComponent, InputComponent> engine;
Run Code Online (Sandbox Code Playgroud)

宣布,电话:

engine.ordinal<PhysicsComponent>();
Run Code Online (Sandbox Code Playgroud)

将返回1并且使用InputComponent而不是PhysicsComponent的类似调用将返回2.

是否可能,如果是的话,怎么会这样呢?

Bar*_*rry 11

所以,你想找到的索引ComponentComponents...

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>
{ };
Run Code Online (Sandbox Code Playgroud)

用法:

template <typename Component> 
size_t ordinal() { return index<Component, Components...>::value; }
Run Code Online (Sandbox Code Playgroud)

正如构造的那样,试图得到ordinal一个Component不存在Components...将是一个编译错误.这似乎合适.