获取当前持有的std

获取当前持有的std

本文介绍了获取当前持有的std :: variant的typeid(例如boost :: variant type())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从boost :: variant迁移到std :: variant,并遇到了障碍.

I've migrated from boost::variant to std::variant, and hit a snag.

我在boost'type()'中使用了一个不错的函数,该函数可以让您获取当前持有的typeid.参见 https://www.boost. org/doc/libs/1_48_0/doc/html/boost/variant.html#id1752388-bb

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

如何使用std :: variant实现此目标?

How can this be achieved with std::variant?

我在'type_index'上有一个无序的映射键,其中包含一些值'std :: function'.根据类型的不同,我的变体将确定我从地图上获取的功能以进行某些操作. (我的代码太大了,无法发布.)

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).

除了为特定的std :: variant编写特定的访问者之外,还有其他实现思路吗?也许在std :: variant上使用'index()'函数,然后索引到变量的类型列表中?像这样:如何从元组中获取第N个类型?

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 );
}

或者

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.

这篇关于获取当前持有的std :: variant的typeid(例如boost :: variant type())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:46