所以我刚开始为我的代码添加选项支持。我可以自己做,也可以使用boost的程序选项。唯一阻止我使用boost的东西是我正在添加到项目中的另一个依赖项。但是,如果它能够轻松处理复杂对象的解析,我更愿意付出代价。
我刚刚根据示例尝试了类似的东西,但它不起作用:
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <iostream>
#include <fstream>
#include <iterator>
using namespace std;
struct Grid{
double xmin, xmax;
};
int main(int ac, char* av[])
{
try {
Grid g;
po::options_description cmd("Allowed options");
cmd.add_options()
("help", "produce help message")
("Grid", "grid information")
;
po::variables_map vm;
store(parse_command_line(ac, av, cmd), vm);
notify(vm);
if (vm.count("help")) {
cout << cmd << "\n";
return 0;
}
g = vm["Grid"].as<Grid>();
cout << g.xmin << " " << g.xmax << endl;
}
catch(exception& e)
{
cout << e.what() << "\n";
return 1;
}
return 0;
当我使用./a.out --Grid {-1, 1}
运行代码时,我得到boost::bad_any_cast: failed conversion using boost::any_cast
。我不明白这意味着什么,但我的猜测是我无法正确地告诉我对象类型Grid
的提升。如何使用boost正确执行此操作?
答案 0 :(得分:4)
首先,简单的方法是使用po::value<std::vector<double>>()->multitoken(),
:
但是,您需要传递这样的参数:--Grid -1 1
int main(int ac, char* av[])
{
try {
po::options_description cmd("Allowed options");
cmd.add_options()
("help", "produce help message")
("Grid", po::value<std::vector<double>>()->multitoken(),
"grid information")
;
po::variables_map vm;
store(parse_command_line(ac, av, cmd), vm);
notify(vm);
if (vm.count("help")) {
cout << cmd << "\n";
return 0;
}
Grid g{vm["Grid"].as<std::vector<double>>()[0],
vm["Grid"].as<std::vector<double>>()[1]};
cout << g.xmin << " " << g.xmax << endl;
}
catch(exception& e)
{
cout << e.what() << "\n";
return 1;
}
}
如果您想传递--Grid {-1,1}
之类的参数,可以添加operator>>
并自己解析std::string
:
std::istream& operator>>(std::istream &in, Grid &g)
{
// Note that this code does not do any error checking, etc.
// It is made simple on purpose to use as an example
// A real program would be much more robust than this
std::string line;
std::getline(in, line);
std::stringstream ss(line);
char bracket, comma;
double xmin, xmax;
ss >> bracket >> xmin >> comma >> xmax;
g = Grid{xmin, xmax};
return in;
}
//...
Grid g;
try {
//...
cmd.add_options()
("help", "produce help message")
("Grid", po::value(&g), "grid information")
;
//...
cout << g.xmin << " " << g.xmax << endl;
另请注意,在--Grid {-1,1}
中,没有空格:-1,1
,而不是-1, 1
。这是因为line
只会包含{-1,
。
如果您需要空格,以下是使用custom validator和--Grid {-1, 1}
解析multitoken
的示例:
// Showing only changes, rest of the code is the same
void validate(boost::any& v, const std::vector<std::string>& val,
Grid*, double)
{
std::stringstream ss(val[0]);
char bracket;
double xmin, xmax;
ss >> bracket >> xmin;
ss.str(val[1]);
ss >> xmax;
v = Grid{xmin, xmax};
}
po::options_description cmd("Allowed options");
cmd.add_options()
("help", "produce help message")
("Grid", po::value(&g)->multitoken(), "grid information")
;