2015-12-11 42 views
0

我需要使用以下語法的程序: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); 

加速.Program_options用於捕捉第一個參數(config.ini)?或者沒有選項說明符的任何值?

回答

1

根據documentation,這些可以用位置參數來處理。您可以在下指定位置選項

如果我瞭解您的預期功能,下面介紹如何將它們放在一起以便在上面的示例中使用。

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

非常感謝,它的工作原理!請注意:在添加位置描述之前,還需要將''config-file''添加到'desc'。 – vladon