Get index by type in std::variant

前端 未结 5 1192
暗喜
暗喜 2020-12-10 13:19

Is there a utility in the standard library to get the index of a given type in std::variant? Or should I make one for myself? That is, I want

5条回答
  •  遥遥无期
    2020-12-10 14:18

    We could take advantage of the fact that index() almost already does the right thing.

    We can't arbitrarily create instances of various types - we wouldn't know how to do it, and arbitrary types might not be literal types. But we can create instances of specific types that we know about:

    template  struct tag { }; // <== this one IS literal
    
    template 
    struct get_index;
    
    template  
    struct get_index>
        : std::integral_constant...>(tag()).index()>
    { };
    

    That is, to find the index of B in variant we construct a variant, tag, tag> with a tag and find its index.

    This only works with distinct types.

提交回复
热议问题