繁体   English   中英

Boost.Program_options-空闲值(无选项的值)

[英]Boost.Program_options - free value (value without an option)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM