Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get currently held typeid of std::variant (like boost::variant type())

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?

like image 683
GreekFire Avatar asked Dec 09 '18 21:12

GreekFire


1 Answers

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.

like image 105
Yakk - Adam Nevraumont Avatar answered Nov 15 '22 02:11

Yakk - Adam Nevraumont