日前项目当中用到boost::program_options这个库,主要是用来parse commandline的,大致的功能如下:
以下代码摘自boost help
-
// Declare the supported options.
-
po::options_description desc("Allowed options");
-
desc.add_options()
-
("help", "produce help message")
-
("compression", po::value<int>(), "set compression level")
-
;
-
-
po::variables_map vm;
-
po::store(po::parse_command_line(ac, av, desc), vm);
-
po::notify(vm);
-
-
if (vm.count("help")) {
-
cout << desc << "n";
-
return 1;
-
}
-
-
if (vm.count("compression")) {
-
cout << "Compression level was set to "
-
<< vm["compression"].as<int>() << ".n";
-
} else {
-
cout << "Compression level was not set.n";
-
}
利用这个库,可以生成类似下列的help信息:
-
$ bin/gcc/debug/first --help
-
Allowed options:
-
--help : produce help message
-
--compression arg : set compression level
这边的设置功能很有意思,一条条直接插入,很简洁,如下:
-
desc.add_options()
-
("help", "produce help message")
-
("compression", po::value<int>(), "set compression level")
-
;
如何实现这样的功能的?其实在看了boost的源代码之后,就可以知道这个是利用重载()运算符实现的,下面,我简化了boost库的代码,写了一个测试的程序,如下。
-
#include <boost/shared_ptr.hpp>
-
-
#include <iostream>
-
#include <string>
-
#include <vector>
-
using namespace std;
-
-
namespace program_option_own
-
{
-
class program_option_data
-
{
-
private:
-
string _name;
-
string _description;
-
public:
-
program_option_data( const char* name, const char * description):
-
_name(name), _description(description)
-
{
-
};
-
string& name(){return _name;};
-
string& description(){return _description;};
-
};
-
-
class program_option_init
-
{
-
private:
-
string _optname;
-
std::vector < boost::shared_ptr<program_option_data> > m_options;
-
public:
-
program_option_init(const char* name):_optname(name){};
-
program_option_init& add_option(){return *this;};
-
program_option_init& add(boost::shared_ptr<program_option_data> desc){
-
m_options.push_back(desc);
-
return *this;
-
};
-
program_option_init& operator()(const char * name,
-
const char * description){
-
boost::shared_ptr<program_option_data> d(
-
new program_option_data(name, description));
-
add(d);
-
return *this;
-
};
-
friend ostream & operator << (ostream&, program_option_init &);
-
};
-
ostream & operator << (ostream & o, program_option_init & p)
-
{
-
o << p._optname << endl;
-
for (int i = 0; i < p.m_options.size(); i++)
-
o << p.m_options[i]->name() << " " << p.m_options[i]->description() << endl;
-
}
-
}
-
int main( int argc, char ** argv )
-
{
-
using namespace program_option_own;
-
program_option_init set("title");
-
set.add_option()
-
("--help", "show help")
-
("--c", "configuration")
-
;
-
cout << set;
-
-
return 0;
-
}
简化版当中,定义了2个类,
program_option_data用来存储单个插入信息的string,program_option_init用来存储所有的program_option_data,并将它们保存在一个vector里面,用适当的方法打印出来。
下列是打印出来的值
-
[root@jsu27 program_option_own]# ./program_option_own.bin
-
title
-
--help show help
-
--c configuration
该方法设置简单明了,值得我们学习。
阅读(8800) | 评论(1) | 转发(1) |