c++ - Boost.Program_options - 免费值(没有选项的值)

标签 c++ boost boost-program-options

我需要为程序使用以下语法:

myprogram config.ini --option1 value --option2 value2

我正在使用如下内容:

  namespace po = boost::program_options;

  po::options_description desc("Allowed options");
  desc.add_options()
        ("option1", po::value<std::string>()->required(), "option 1")
        ("option2", po::value<uint16_t>()->required(), "option 2")
        ("help", "this message");

  po::variables_map opts;
  po::store(po::command_line_parser(argc, argv).options(desc).run(), opts);

  if (opts.count("help")) {
        show_help(desc);
        return 0;
  }

  po::notify(opts);

Boost.Program_options 能否用于捕获第一个参数 (config.ini)?或者没有选项说明符的任何值?

最佳答案

根据documentation ,这些可以用位置参数处理。

你可以找到另一个很好的例子here ,在指定位置选项下。

如果我了解您的预期功能,您可以按照以下方式将其整合到上面的示例中。

namespace po = boost::program_options;

po::options_description desc( "Allowed options" );

desc.add_options( )
    ( "option1", po::value<std::string>( )->required( ), "option 1" )
    ( "option2", po::value<uint16_t>( )->required( ), "option 2" )
    // this flag needs to be added to catch the positional options
    ( "config-file", po::value<std::string>( ), ".ini file" )
    ( "help", "this message" );

po::positional_options_description positionalDescription;

// given the syntax, "config.ini" will be set in the flag "config-file"
positionalDescription.add( "config-file", -1 );

po::variables_map opts;

po::store( 
    po::command_line_parser( argc, argv )
        .options( desc )
        // we chain the method positional with our description
        .positional( positionalDescription )
        .run( ), 
    opts 
);

if (opts.count( "help" )) 
{
    show_help( desc );

    return 0;
}

po::notify( opts );

关于c++ - Boost.Program_options - 免费值(没有选项的值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219474/

相关文章:

c++ - 在模块化程序中使用 Boost.Program_options

c++ - 从 AudioInputIOProc 创建 CMSampleBufferRef

c++ - Clang AST 访问者,避免遍历包含文件

c++ - int main() argv 参数问题

c++ - 使用 MSVC 14.0 (VS 2015) 编译 Boost 时编译器版本未知

c++ - Boost.Program_Options:为什么 options_description_easy_init::operator() 没有 std::string 的重载?

c++ - c++ 编译的 DLL 可以在没有大小差异的情况下在代码上有所不同吗?

c++ - 装饰器还是抽象基类?两者都不对

c++ - 评估 C++ 字符串中的表达式 : "Hi ${user} from ${host}"

c++ - Boost Program Options 依赖选项