c++ - 在 C++ 中运行时获取变体中包含的类型?

标签 c++ c++11 c++17 pybind11

在 C++ 中,如何在运行时打印变体中包含的类型?

我的用例:使用 pybind11 将值字典从 Python 传递到 C++ ,我想打印出接收到的类型。

最佳答案

您可以通过 std::visit 和一些类型名打印库(例如 Boost.TypeIndex)获得通用解决方案。示例性解决方案:

#include <iostream>
#include <type_traits>
#include <variant>

#include <boost/type_index.hpp>

int main()
{
  std::variant<char, bool, int, double> v;

  auto print_variant_type =
      [](auto&& value)
      {
          using T = std::decay_t<decltype(value)>;
          std::cout << boost::typeindex::type_id<T>().pretty_name() << std::endl;
      };

  v = 'a';
  std::visit(print_variant_type, v); // prints out "char"

  v = true;
  std::visit(print_variant_type, v); // prints out "bool"

  v = 1;
  std::visit(print_variant_type, v); // prints out "int"

  v = 1.0;
  std::visit(print_variant_type, v); // prints out "double"
}

现场演示:https://godbolt.org/z/Web5zeGof

唯一的缺点是它可以为类型别名(例如 std::string)的库类型打印“丑陋”的类型名称。可能更适合您的特定变体实例的替代方法可能是使用从变体索引到类型名称的映射:

using variant_type = std::variant<char, bool, int, double, std::string>;

static const std::array variant_type_names =
  { "char", "bool", "int", "double", "std::string" };

void print_variant_type(const variant_type& v)
{
  assert(v.index() < variant_type_names.size());
  std::cout << variant_type_names[v.index()] << std::endl;
}

int main()
{
  variant_type v;

  v = 'a';
  print_variant_type(v); // prints out "char"

  v = true;
  print_variant_type(v); // prints out "bool"

  v = 1;
  print_variant_type(v); // prints out "int"

  v = 1.0;
  print_variant_type(v); // prints out "double"

  v = std::string("some string");
  print_variant_type(v); // prints out "std::string"
}

现场演示:https://godbolt.org/z/9na1qzEKs

关于c++ - 在 C++ 中运行时获取变体中包含的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74386543/

相关文章:

c++ - 当我在子类中调用函数时,它会调用父类函数

c++ - C++ nullptr实现如何工作?

c++ - 如何将多个集成订单整合到我的Integrator类中?

c++ - 如何将变量的元素转换为 std::string ( c++ )

c++ - 如何在构造函数的参数中分配的对象上调用 delete

C++ : has_trivial_X type traits

c++ - 从 .dat 文件中读取数字,然后计算标准差

c++ - 使用 STL 的图形(列表 vector ,即邻接列表)- C++

c++ - STM32 LWIP PPPos 实现

c++ - 如何仅使用 C++ 标准库构建句子解析器?