boost库中program_opition的使用
来源:互联网 发布:淘宝销量排行榜2017 编辑:程序博客网 时间:2024/05/14 07:48
在写程序的时候,我们经常需要传放一些参数,或者通过配置文件传入一些参数,program_opition库为我们提供了一个简单而实用的解决方案,避免了每次写console程序时重复写命令解析的代码。
下面以一个常见的需求为例来简单说明一下此库的用法。
程序regist需要一个配置文件client.conf,里面存储了一些启动参数。启动程序的时候,我们也希望可以在命令行中指定一些参数,并且如果这些参数也在配置文件中出现,那么以命令行中的值为标准。
#include <fstream>#include <string>#include <boost/program_options/variables_map.hpp>#include <boost/program_options.hpp>#include <boost/program_options/parsers.hpp>#include <boost/program_options/options_description.hpp>namespace po = boost::program_options;using std::string;using std::cout;using std::endl;using std::ifstream;int main(int argc, char** argv) { po::options_description desc("Allowed options"); string clientType; desc.add_options() ("serverRealIP", po::value<string>(), "real ip of the server") ("clientType", po::value<string>(&clientType), "the type of client"); po::variables_map vm; ifstream confFile("client.conf"); po::store(po::parse_command_line(argc, argv, desc), vm); po::store(po::parse_config_file(confFile, desc, true), vm); po::notify(vm); if(vm.count("serverRealIP")) cout<<"serverRealIP: "<<vm["serverRealIP"].as<string>()<<endl; cout<<"clientType: "<<clientType<<endl; return 0;}
client.conf 配置文件内容如下
#this is comment
serverRealIP=211.65.xx.xx
serverVPNIP=192.168.xx.xx
registDaemonPort=9999
#the client type
clientType=dom0
执行程序
./regist
输出
serverRealIP: 211.65.xx.xxclientType: dom0
带参数 ./regist --serverRealIP 192.168.100.1 --clientType dom1
输出
serverRealIP: 192.168.100.1clientType: dom1
可以看到解析出来的值换成了命令行给的值。
下面对程序做一点简单说明:
options_description用来存储配置中出现的键值对的容器,使用 add_options()方法加入新的键值对的描述。
variables_map用来存储最后的结果。
store方法将解析出来的键值对保存进variable_map,注意,如果一个键在vm中已经存在了,那么再次出现的时候,其值不会改变,依旧以原来的为准。所以两次调用store方法时,先将命令行的结果存入了vm,这样对在命令行和配置文件中都出现的键,其值以命令行为准。
对于结果的读取有两种方法
一种是像代码中werverRealIP的读取,当存在时,调用vm["serverRealIP"].as<string>() 来取得, as<T>中的T为值的类型,由库已经做好了转换。
另一种如代码中的clientType,在调用add_opitions方法时,即传入了clientType变量,做为保存值的变量,这样,当找到了其值的时候,就自动存入此变量中。
还有其他更多复杂用法,请参考官方文档
- boost库中program_opition的使用
- boost库中program_opition的使用 .
- boost中filesystem库的使用
- boost库中线程的使用
- boost中regex的使用
- boost中bind的使用
- boost中format的使用
- boost中bind的使用
- boost库的使用
- Boost库的使用
- 【Boost】boost库中function的用法
- 【Boost】boost库中bind的用法
- vc2008中使用boost库
- vc2008中使用boost库
- vs中使用boost库
- 【Boost】boost库中function和bind一起使用的技巧(一)
- 【Boost】boost库中function和bind一起使用的技巧(二)
- Boost.Python:安装使用(兼具Boost.Python库中Python编译版本的修改)
- IE6解析css的常见错误
- css控制图片圆角
- erlang随机数的生成
- hdu1260
- 解决OracleDBConsoleorcl不能启动
- boost库中program_opition的使用
- 一段生活的开始
- Android之SurfaceView学习
- more newfile.txt | grep -0 server | wc -l
- ubuntu11.10配置android4.0的编译环境
- Java编程的几个最佳实践
- android在线播放mp4/3gp
- 使用directshow的一点路径包含问题
- 一步一步复习数据结构和算法基础-栈和队列(1)