Is there any way I can allow multiple occurrences of custom type (struct
) in boost::program_options
? I found the various sources specifying this can be done using std::vector
but I wanted to achieve the same using custom data type. However this struct do contain a std::vector
where I want to store the data.
A code sample would really help a lot.
But, since your struct will contain the vector, why not bind that vector?
Simple example:
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/cmdline.hpp>
#include <iostream>
#include <vector>
struct my_custom_type {
std::vector<std::string> values;
friend std::ostream& operator<<(std::ostream& os, my_custom_type const& mct) {
std::copy(mct.values.begin(), mct.values.end(), std::ostream_iterator<std::string>(os << "{ ", ", "));
return os << "}";
};
};
int main(int argc, char** argv) {
namespace po = boost::program_options;
my_custom_type parse_into;
po::options_description desc;
desc.add_options()
("item", po::value<std::vector<std::string> >(&parse_into.values), "One or more items to be parsed")
;
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc, po::command_line_style::default_style), vm);
vm.notify();
std::cout << "Parsed custom struct: " << parse_into << "\n";
} catch(std::exception const& e) {
std::cerr << "Error: " << e.what() << "\n";
}
}
When called with 26 arguments, like ./test --item={a..z}
it prints:
Parsed custom struct: { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, }
If you want to "automatically" treat the conversions in a "special" way, you can look at