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
One fun way to do this is to take your variant and turn it into a custom class hierarchy that all implement a particular static member function with a different result that you can query.
In other words, given variant, create a hierarchy that looks like:
struct base_A {
static integral_constant get(tag);
};
struct base_B {
static integral_constant get(tag);
};
struct base_C {
static integral_constant get(tag);
};
struct getter : base_A, base_B, base_C {
using base_A::get, base_B::get, base_C::get;
};
And then, decltype(getter::get(tag is the index (or doesn't compile). Hopefully that makes sense.
In real code, the above becomes:
template struct tag { };
template
struct base {
static std::integral_constant get(tag);
};
template
struct getter_impl;
template
struct getter_impl, Ts...>
: base...
{
using base::get...;
};
template
struct getter : getter_impl, Ts...>
{ };
And once you establish a getter, actually using it is much more straightforward:
template
struct get_index;
template
struct get_index>
: decltype(getter::get(tag()))
{ };
That only works in the case where the types are distinct. If you need it to work with independent types, then the best you can do is probably a linear search?
template
struct get_index;
template
struct get_index_impl
{ };
template
struct get_index_impl
: std::integral_constant
{ };
template
struct get_index_impl
: get_index_impl
{ };
template
struct get_index>
: get_index_impl<0, T, Ts...>
{ };