【问题标题】:Boost program option: force "="升压程序选项:强制“=”
【发布时间】:2013-10-17 09:12:40
【问题描述】:

我正在使用boost::program_options,这个问题只是审美问题。

如何强制std::string 选项(或更好的all 选项)仅使用带有“=”的长格式?

现在,我看到的只是“=”被强制用于我的 int 选项,而字符串没有使用等号:

    po::options_description desc("Allowed options");
    desc.add_options()
        (opt_help, "Show this help message")
        (opt_int,  po::value<int>()->implicit_value(10), "Set an int")
        (opt_str,  po::value<std::string>()->implicit_value(std::string()), "Set a string")
    ;

以上将所有选项显示为--help--int=4--str FooBar。我只想要--option=something 形式的选项。

我尝试了一些样式,但没有找到合适的。

干杯!

【问题讨论】:

    标签: c++ boost command-line boost-program-options


    【解决方案1】:

    如果不编写自己的解析器,就无法做到这一点。

    http://www.boost.org/doc/libs/1_54_0/doc/html/program_options/howto.html#idp123407504

    std::pair<std::string, std::string> parse_option(std::string value)
    {
       if (value.size() < 3)
       {
          throw std::logic_error("Only full keys (--key) are allowed");
       }
       value = value.substr(2);
       std::string::size_type equal_sign = value.find('=');
       if (equal_sign == std::string::npos)
       {
          if (value == "help")
          {
             return std::make_pair(value, std::string());
          }
          throw std::logic_error("Only key=value settings are allowed");
       }
       return std::make_pair(value.substr(0, equal_sign),
       value.substr(equal_sign + 1));
    }
    
    // when call parse
    
    po::store(po::command_line_parser(argc, argv).options(desc).
    extra_parser(parse_option).run(), vm);
    

    但是,您可以通过更简单的方式来做到这一点

    void check_allowed(const po::parsed_options& opts)
    {
       const std::vector<po::option> options = opts.options;
       for (std::vector<po::option>::const_iterator pos = options.begin();
            pos != options.end(); ++pos)
       {
          if (pos->string_key != "help" &&
          pos->original_tokens.front().find("=") == std::string::npos)
          {
             throw std::logic_error("Allowed only help and key=value options");
          }
       }
    }
    
    po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).
    style(po::command_line_style::allow_long | 
    po::command_line_style::long_allow_adjacent).run();
    check_allowed(opts);
    

    因此,在这种情况下,boost::po 解析并且您只需检查即可。

    【讨论】:

    • 太糟糕了,我发现“总是平等”的风格非常整洁。谢谢!
    猜你喜欢
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多