Boost.Program_options-自由值(没有选项的值)

Boost.Program_options - free value (value without an option)

本文关键字:选项 options- 自由 Boost Program      更新时间:2023-10-16

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

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)?或者任何没有选项说明符的值?

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

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

如果我理解您想要的功能,以下是您将如何将其结合在上面的示例中工作。

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 );