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 <typename> struct tag { }; // <== this one IS literal
template <typename T, typename V>
struct get_index;
template <typename T, typename... Ts>
struct get_index<T, std::variant<Ts...>>
: std::integral_constant<size_t, std::variant<tag<Ts>...>(tag<T>()).index()>
{ };
That is, to find the index of B
in variant<A, B, C>
we construct a variant<tag<A>, tag<B>, tag<C>>
with a tag<B>
and find its index.
This only works with distinct types.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…