如何在Boost程序选项中获得更好的错误消息

use*_*900 9 c++ boost boost-program-options

在下面的代码中,我使用程序选项从命令行或文件中读取参数.此外,可以通过ConfigProxy :: setConfig在运行时以编程方式设置选项

po::options_description desc("Allowed options");
desc.add_options()
    ...
    ("compression", po::value<int>(), "set compression level");

po::variables_map vm;

class ConfigProxy
{
     template< typename T>
     void setConfig( const std::string key, const T value ){
          ... // check if the key exists in variable map "vm"

          // key exists, set the value
          runtimeConfig[key] = po::variable_value( boost::any(value), false);
     }

     po::variable_value& operator[] (const std::string key) const{
          ...
          // if exists in runtimeConfig return the value in runtimeConfig
          // of type program_options::variable_value
          ...
          // else return value in variable map "vm"
     }

     std::map<std::string, boost::program_options::variable_value> runtimeConfig;
}
Run Code Online (Sandbox Code Playgroud)

通过ConfigProxy,检索选项值

if( vm.count("compression") ){
    int value = proxyConfig["compression"].as<int>();
    ...
}
Run Code Online (Sandbox Code Playgroud)

然而,如果由用户提供的"压缩"选项值是错误的类型,例如

configProxy.setConfig("compression", "12" );
...
int value = configProxy["compression"].as<int>(); // was set as string
Run Code Online (Sandbox Code Playgroud)

然后抛出异常

what():  boost::bad_any_cast: failed conversion using boost::any_cast
Run Code Online (Sandbox Code Playgroud)

该例外清楚地显示了类型转换问题.但是该消息似乎对用户找不到哪个选项导致错误有帮助.

有没有更好的方法来告知用户这种类型的错误,而不是抛出bad_any_cast异常?

-----编辑--------------------------

感谢Luc Danton和Tony,我发现程序选项如何显示错误.

void validate(boost::any& v,
              const std::vector< std::basic_string<charT> >& xs,
              T*, long)
{
    validators::check_first_occurrence(v);
    std::basic_string<charT> s(validators::get_single_string(xs));
    try {
        v = any(lexical_cast<T>(s));
    }
    catch(const bad_lexical_cast&) {
        boost::throw_exception(invalid_option_value(s));
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为,通过实现逻辑,我可以摆脱bad_any_cast异常.

Luc*_*ton 4

你尝试过吗?

("compression", po::value<int>(), "set compression level");
Run Code Online (Sandbox Code Playgroud)

注意po::value<int>()。您在此处指定关联值的类型int。当用户传递 Boost.ProgramOptions 无法转换为的内容时int,程序将失败并显示错误消息:

error: in option 'compression': invalid option value
Run Code Online (Sandbox Code Playgroud)

毕竟,这是图书馆的作用之一。

您必须这样做的原因vm["compression"].as<int>()是因为 的类型compression是在函数调用中指定的(括号中的三元组),这是运行时世界中的东西。这不会影响 的返回类型vm["compression"],因此它需要是某种动态类型模拟。因此,boost::any_cast_failed当您查询未指定的类型时会出现异常。