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

allow multiple occurrences of custom type using Boost::program_options

本文关键字:自定义 许多次 类型 options Boost program 使用      更新时间:2023-10-16

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

代码示例真的很有帮助。

但是,既然结构体将包含vector,为什么不绑定该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, }

如果您想以"特殊"的方式"自动"处理转换,您可以查看

  • 自定义验证器(http://www.boost.org/doc/libs/1_59_0/doc/html/program_options/howto.html#idp343336928)
  • 自定义通知器(一个简单的例子见例63.1)。