1

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.

Pranav
  • 560
  • 1
  • 8
  • 21

1 Answers1

0

A code sample would really help a lot.

But, since your struct will contain the vector, why not bind that vector?

Simple example:

Live On Coliru

#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

sehe
  • 374,641
  • 47
  • 450
  • 633
  • thank you very much for the code snippet. Binding the vector should help in my situation. Will this work when we give input such as `./test --item=a --item=b`? – Pranav Sep 22 '15 at 20:56
  • ... Yes. It's exactly what I did... Did you see the live sample? – sehe Sep 22 '15 at 21:15
  • 1
    In case you didn't know, `--item={a,b,c}` is brace expansion in `bash` and expands to `--item=a --item=b --item=c` – sehe Sep 22 '15 at 21:38