c++ - Boost 程序选项遍历 variables_map

标签 c++ boost c++11 boost-program-options

po::options_description desc("This are the options that are available");
    desc.add_options()("help", "print help")(
        "deer", po::value<uint32_t>(), "set how many deer you want")(
        "rating", po::value<uint32_t>(), "how good ?")(
        "name", po::value<std::string>(), "and your name is ... ?");

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);

在接下来的代码部分中,我尝试遍历 vm

for (const auto& it : vm) {
      std::cout << it.first.c_str() << " "
                << it.second.as<it.pair::second_type>() << "\n";
    }

这里的重点是 vm 包含相同类型的 keys,但是不同类型的值,在这个例子中我有 uint32_tstd::string 混合。

我如何遍历这种容器?我想避免冗长的方法,所以我试图只迭代这个数据结构。

编辑:

我忘记写下来了,但是很明显

namespace po = boost::program_options;

最佳答案

boost variable_map使用 boost::any作为值,因此您可以尝试使用 boost::any_cast<T>找出类型。 也许是这样的

for (const auto& it : vm) {
  std::cout << it.first.c_str() << " ";
  auto& value = it.second.value();
  if (auto v = boost::any_cast<uint32_t>(&value))
    std::cout << *v;
  else if (auto v = boost::any_cast<std::string>(&value))
    std::cout << *v;
  else
    std::cout << "error";
}

关于c++ - Boost 程序选项遍历 variables_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008893/

相关文章:

c++ - 无法在C++中包含头文件

c++ - 如何使用 C++ boost 库获取文件权限?

c++ - 标准::线程 C++。更多线程相同数据

c++ - C++中类的静态成员

c++ - 我用宏执行了以下代码

c++ - 使用 Boost Asio 接受 IPv6 链接范围地址

c++ - 离开范围时,我的 boost managed_shared_memory 似乎没有从内存空间取消映射

c++ - 如何在 C++ 中使用 Null Lambda?

c++0x 库在任何编译器中的可用性?

c# - 如何解决 "Native DLL libmbusmaster.dll is missing! Please deploy the DLL file into the same directory as mbusmaster.net.dll."的问题