martinmoene / variant-lite

variant lite - A C++17-like variant, a type-safe union for C++98, C++11 and later in a single-file header-only library
Boost Software License 1.0
239 stars 25 forks source link

index_of() method should be static #30

Closed xirius closed 5 years ago

xirius commented 5 years ago

I find that non-standard index_of() method is very handy. But it should be static to be really useful. As the variant types are known at the definition they should be queried without the need of the actual object:

using Value = variant<int, double, std::string>;
Value value{"Some string"};

switch (value.index())
{
    case Value::index_of<int>():
        // do something
        break;
    case Value::index_of<double>():
      // do something
      break;
    case Value::index_of<std::string>():
      // do something
      break;
  }

Unfortunately this code doesn't compile (with gcc 7) because index_of() is not a constexpr even if it is declared as such:

template< class T >
variant_constexpr std::size_t index_of() const variant_noexcept
{
    return detail::typelist_index_of<variant_types, typename detail::remove_cv<T>::type >::value;
}

It should be

template< class T >
static variant_constexpr std::size_t index_of() variant_noexcept
{
    return detail::typelist_index_of<variant_types, typename detail::remove_cv<T>::type >::value;
}

As this function is currently non static the compiler cannot precompile it as there is no constexpr std::variant constructors available. By making it static it solves this issue.