通过使用自定义验证器和boost::program_options::value::multitoken,您可以获得所需的结果:
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <boost/program_options.hpp>
// Holds parameters for seed/expansion model
struct Model
{
std::string type;
boost::optional<float> param1;
boost::optional<float> param2;
};
// Called by program_options to parse a set of Model arguments
void validate(boost::any& v, const std::vector<std::string>& values,
Model*, int)
{
Model model;
// Extract tokens from values string vector and populate Model struct.
if (values.size() == 0)
{
throw boost::program_options::validation_error(
"Invalid model specification");
}
model.type = values.at(0); // Should validate for A/B
if (values.size() >= 2)
model.param1 = boost::lexical_cast<float>(values.at(1));
if (values.size() >= 3)
model.param2 = boost::lexical_cast<float>(values.at(2));
v = model;
}
int main(int argc, char* argv[])
{
Model seedModel, expansionModel;
namespace po = boost::program_options;
po::options_description options("Generic options");
options.add_options()
("seed",
po::value<Model>(&seedModel)->multitoken(),
"seed graph model")
("expansion",
po::value<Model>(&expansionModel)->multitoken(),
"expansion model")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
po::notify(vm);
std::cout << "Seed type: " << seedModel.type << "\n";
if (seedModel.param1)
std::cout << "Seed param1: " << *(seedModel.param1) << "\n";
if (seedModel.param2)
std::cout << "Seed param2: " << *(seedModel.param2) << "\n";
std::cout << "Expansion type: " << expansionModel.type << "\n";
if (expansionModel.param1)
std::cout << "Expansion param1: " << *(expansionModel.param1) << "\n";
if (expansionModel.param2)
std::cout << "Expansion param2: " << *(expansionModel.param2) << "\n";
return 0;
}
该validate
功能可能需要更严格,但您明白了。
这对我来说是编译和工作的。