How to solve “boost::bad_any_cast: failed conversion using boost::any_cast” when using boost program options?

后端 未结 4 1128
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 16:40
//Using boost program options to read command line and config file data
    #include 
    using namespace std;
    using namespace b         


        
4条回答
  •  醉梦人生
    2021-01-01 17:11

    This same message can also occur if you are not handling optional arguments correctly.

    Sam's solution nails required arguments and the OP's code suggests required - just mark them required. For optional inputs, the Boost PO tutorial gives us a template for checking if the option exists before converting it:

    if(vm.count("address")) 
    {
        const std::string address = vm["IPAddress"].as();
        std::cout << "address: " << address << std::endl;
    }
    if(vm.count("port")) 
        const std::string port = vm["Port"].as();
        std::cout << "port: " << port << std::endl;
    }
    

    My problem - I had copied/pasted and forgotten to align the if test with the usage!

提交回复
热议问题