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.
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:Unfortunately this code doesn't compile (with gcc 7) because
index_of()
is not aconstexpr
even if it is declared as such:It should be
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.