首页 > 解决方案 > 获取当前持有的 std::variant 的 typeid(如 boost::variant type())

问题描述

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

我在 boost 'type()' 中使用了一个很好的函数,它可以让你获得当前持有的 typeid。见https://www.boost.org/doc/libs/1_48_0/doc/html/boost/variant.html#id1752388-bb

如何使用 std::variant 实现这一点?

我在“type_index”上有一个无序映射键,它包含一些值“std::function”。我的变体,取决于类型,将决定我从地图中抓取什么功能来做一些操作。(我的代码太大而无法发布)。

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

标签: c++boosttypeidstd-variant

解决方案


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

这使您可以询问其他不活动的索引。


推荐阅读