|
Boost : |
Subject: [boost] [program_options] comma separated options
From: Alain Miniussi (Alain.Miniussi_at_[hidden])
Date: 2014-02-10 05:34:26
Hi,
Someone asked me if it was possible to "easily" specify an option that
would allow to specify a vector of values.
The first options that came in mind was to use "multitoken". But that
solution had to drawback in that situation:
- ambiguous with respect to positional parameters
- clumsy when you want to allow options to be specified in files, since
you have to write:
option 12
option 42
...
instead of:
option 12 42 19
So I though about using a custom validator, which implies introducing a
new type too, if I understand correctly.
Something along the lines of:
=======================
...
template<typename T>
struct option_sequence {
std::vector<T> values;
};
template<typename T>
void validate(boost::any& v,
const std::vector<std::string>& values,
option_sequence<T>* target_type, int)
{
namespace po = boost::program_options;
namespace alg = boost::algorithm;
std::vector<T> result;
typedef std::vector<std::string> strings;
for ( strings::const_iterator iter = values.begin(); iter !=
values.end();
++iter ) {
strings tks;
alg::split(tks, *iter, alg::is_any_of(":"));
for( strings::const_iterator tk = tks.begin(); tk != tks.end();
++tk) {
result.push_back(boost::lexical_cast<T>(*tk));
}
}
v = option_sequence<T>();
boost::any_cast<option_sequence<T>&>(v).values.swap(result);
}
int
main(int argc, char* argv[]) {
....
desc.add_options()
("values,v", po::value<option_sequence<int> >(), "a vector of
':' separated values as in \"12:42:-20\".");
===================
Obviously, one could think that some flexibility could be added
(separators for starters) but you get the idea.
Is that the right way to go (the intermediate option_sequence template
seems clumsy for the user (but you need to distinguish from
std::vector's) and if yes, could such a thing be added to the library ?
(if yes a could propose a patch for consideration).
Cheers
-- ===================================== Alain Miniussi DSI/Pôle Génie Logiciel Scientifique Observatoire de la Côte d'Azur
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk