boost program_options
一直認為boost都是hpp直接調用就可以了,最近遇到兩個例子都不是這樣的一個是boost的thread,另外一個就是這個了,boost在編譯好之后會有庫文件的,注意不是在當前的libs下面,而是stage/libs下面,我們在使用這個模塊的時候要加上相應的動態或者靜態的庫。
當我們寫一些小程序的時候難免要寫一些輸入參數,當然用linux自帶的也可以
[cpp] view plaincopy
- int next_option;
- /* Parse options. */
- do {
- next_option = getopt_long (argc, argv, short_options, long_options, NULL);
- }while(next_options);
但是我們要寫很多error handing,user manual 之類的, 比較麻煩,而且打印出來的格式也不是很好看。
那boost的program_options可以幫助我們解決這個問題。
boost program_options不僅支持配置command line,而且支持配置像INI一樣的配置文件,這個模塊非常好,下面是對配置文件格式的說明:
語法大致有三條,一個是name value的對應關系,另一個是section的模塊,最后一個是注釋的規范。
Configuration file parser
The parse_config_file
function implements parsing of simple INI-like configuration files. Configuration file syntax is line based:
-
A line in the form:
name
=value
gives a value to an option.
-
A line in the form:
[
section name
]introduces a new section in the configuration file.
-
The
#
character introduces a comment that spans until the end of the line.
The option names are relative to the section names, so the following configuration file part:
[gui.accessibility] visual_bell=yes
is equivalent to
gui.accessibility.visual_bell=yes
如何實現一對多的支持?
如果只是command line里面的很簡單 只要加一個token就可以,但是如果是配置文件的則validate
實現很簡單:
po::value<vector<float> >(&(paralist))->multitoken()
注意利用第三個參數重載
namespace boost{
void validate(boost::any& v,
const vector<string>& values,
vector<float>*, int) {
cout << "hello" << endl;
vector<double> dvalues;
for(vector<string>::const_iterator it = values.begin();
it != values.end();
++it) {
//stringstream ss(*it);
cout<<*it<<endl;
}
}
}
如何支持負數?
負數和program option會有沖突,一般通過加引號來處理,或者通過去除短option,只支持長option
char* v[] = {"name","--IDlist=0","1","200","-2"};
int c = 5;
std::vector<int> IDlist;
namespace po = boost::program_options;
po::options_description commands("Allowed options");
commands.add_options()
("IDlist",po::value< std::vector<int> >(&IDlist)->multitoken(), "Which IDs to trace: ex. --IDlist=0 1 200 -2")
("help","print help")
;
po::variables_map vm;
po::store(parse_command_line(c, v, commands, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);
po::notify(vm);
BOOST_FOREACH(int id, IDlist)
std::cout << id << std::endl;
下面講一下具體的使用體會
1 打印很方便尤其是help manual, 對各種命令的錯誤的提示很好
2 type 和 name直接關聯,根據名字直接讀到變量中
3 支持command和文本配置文件,不同的源之間可以合并使用
4 沒有辦法指定變量的有效范圍。
總之,用了之后頗有點專業軟件的風范。
http://www.boost.org/doc/libs/1_45_0/doc/html/program_options.html
http://stackoverflow.com/questions/2935587/handle-complex-options-with-boosts-program-options/2939249#2939249
RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成