I've migrated from boost::variant to std::variant, and hit a snag.
I was using a nice function in boost 'type()' that lets you get the currently held typeid. See https://www.boost.org/doc/libs/1_48_0/doc/html/boost/variant.html#id1752388-bb
How can this be achieved with std::variant?
I have an unordered map key'd on 'type_index', which holds some value 'std::function'. My variant, depending on the type, will determine what function I grab from the map to do some operation. (The code I have is far too large to post).
Any implementation ideas aside from writing a specific visitor for a particular std::variant? Maybe using the 'index()' function on the std::variant, to then index into the type list of the variant? Somewhat like this: How to get N-th type from a tuple?
template<class V>
std::type_info const& var_type(V const& v){
return std::visit( [](auto&&x)->decltype(auto){ return typeid(x); }, v );
}
Alternatively
template<class...Ts>
std::type_info const& var_type(std::variant<Ts...> const& v, std::optional<std::size_t> idx={}){
if (!idx) idx=v.index();
if(*idx==std::variant_npos) return typeid(void);
const std::array<std::type_info const*, sizeof...(Ts)> infos[]={ &typeid(Ts)... };
return *(infos[*idx]);
}
Which lets you ask about other indexes that are not active.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With