Boost程序选项抛出bad_any_cast异常

boost program options throwing bad_any_cast exception

本文关键字:any cast 异常 bad 程序 选项 Boost      更新时间:2023-10-16

我有以下代码在testpo.cpp:

#include <iostream>
#include <boost/program_options.hpp>
#include <fstream>
int main(int argc, char* argv[]) {
  namespace po = boost::program_options;
  po::options_description config_descriptor;
  po::variables_map vm;
  config_descriptor.add_options()
  ("var1", po::value<int>()->required(), "var1");
  //po::store(po::parse_config_file(input_config_file, config_descriptor, false), vm);
  po::store(po::parse_command_line(argc, argv, config_descriptor), vm);
  po::notify(vm);
  try {
    std::cout << vm.count("var1") << std::endl;
    std::cout << "Count printed" << std::endl;
    if (vm.count("var1") > 0) {
      std::cout << "Imheren";
      std::cout << "var1: " << vm["var1"].as<int>() << std::endl;
    } else {
      std::cout << "Missing var1 in config file" << std::endl;
    }
  } catch (std::exception& e) {
    std::cout << "Exception: " << e.what() << std::endl;
  }
}

我使用以下命令进行编译:

g++ -std=c++11 testpo.cpp -lboost_program_options

我像这样运行:

./a.out --var1 10

得到以下输出:

1
Count printed
Imhere
Exception: boost::bad_any_cast: failed conversion using boost::any_cast

我已经看过这个,但它似乎没有帮助。我不知道我做错了什么。

我的系统的相关配置:

g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
Boost version: 1.58

当我在另一个系统上运行它时,它可以工作,配置:

g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)
Boost version: 1.53

这是一个bug在增强?

由于我刚刚遇到了同样的问题,为了将来参考,我将在这里添加我的答案。

由于

中缺少返回语句而引发异常。
int main

edit: strike that。我真笨,忘了在case语句中加break