使用 Boost::program_options 允许多次出现自定义类型

allow multiple occurrences of custom type using Boost::program_options

有什么方法可以允许在 boost::program_options 中多次出现自定义类型 (struct)?我发现指定这可以使用 std::vector 完成的各种来源,但我想使用自定义数据类型来实现相同的目的。但是这个结构确实包含一个 std::vector 我想存储数据的地方。

代码示例真的很有帮助。

但是,由于您的结构将包含向量,为什么不 绑定 该向量?

简单示例:

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";
    }
}

当使用 26 个参数调用时,如 ./test --item={a..z} 它打印:

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, }

如果您想 "automatically" 以 "special" 的方式处理转化,您可以查看