c++ - 获取当前保存的 std::variant 的 typeid(如 boost::variant type())

标签 c++ boost typeid std-variant

我已经从 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”。根据类型的不同,我的变体将决定我从 map 中获取什么功能来执行某些操作。 (我的代码太大,无法发布)。

除了为特定的 std::variant 编写特定的访问者之外,还有什么实现想法吗?也许在 std::variant 上使用“index()”函数,然后索引到变体的类型列表中?有点像这样: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]);
}

这让您可以询问其他不活跃的索引。

关于c++ - 获取当前保存的 std::variant 的 typeid(如 boost::variant type()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696720/

相关文章:

c++ - 在 C++ 中通过串行发送一个有符号整数作为字节,Arduino 读取它

c++ - Hana BOOST_HANA_DEFINE_STRUCT 不适用于 std::unique_ptr

c++ - 了解 C++ 中映射和 vector 的 typeid.name() 输出

c++ - 如何对模板类中的不同模板参数执行不同的操作?

c++ - type_info 的包装类

c++ - 将键盘输入的文本打印到 GLUT 窗口?

c++ - 在 vector 中查找字符串时遇到麻烦

c++ - 在 C++ 中查找字符串中的子字符串

c++ - CMake 没有找到 Boost

c++ - 为什么 boost::bind 存储传入类型的参数而不是函数期望的类型?