How can I get the index of a type in a variadic class template?

前端 未结 4 476
盖世英雄少女心
盖世英雄少女心 2021-01-03 02:11

I have a variadic Engine template class:

template  class Engine;

I\'d like to assign a number to each compon

4条回答
  •  有刺的猬
    2021-01-03 03:02

    UNTESTED:

    template 
    constexpr int index_of() { return -1; } // type not found
    
    template 
    constexpr int index_of() {
        return std::is_same::value ? N : index_of();
    }
    
    template 
    template 
    constexpr int engine::ordinal() {
        return index_of<0, Component, Components...>();
    }
    

    I could have used structs, but I find this much cleaner (without all the ::type ugliness).

    If you want a compile-time error when the type is not found, change ordinal to:

    template 
    template 
    constexpr int engine::ordinal() {
        static_assert(index_of<0, Component, Components...>()!=-1, "invalid component");
         return index_of<0, Component, Components...>();
    }
    

提交回复
热议问题