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

后端 未结 4 1151
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  旧时难觅i
    2021-01-01 17:29

    Not necessarily the same problem as this guy had but here's something that caught me:

    If you put your type in an anonymous namespace, there will be two classes with the same name but different instances and the casting will fail. For example:

    a.hpp:

    namespace {
    class MyClass {...};
    }
    

    b.cpp:

    #include "a.hpp"
    cli_options.add_options()("test", po::value(), "test desc");
    

    c.cpp:

    #include "a.hpp" // THIS WILL MAKE A DIFFERENT "MyClass"
    vm["test"].as();  // Fails at runtime.
    

    It fails because the MyClass in b.cpp and the one in c.cpp aren't the same class. Because of the anonymous namespace.

    Removing the anonymous namespace solves the problem.

提交回复
热议问题