【问题标题】:allow multiple occurrences of custom type using Boost::program_options允许使用 Boost::program_options 多次出现自定义类型
【发布时间】:2015-09-22 17:58:50
【问题描述】:

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

【问题讨论】:

    标签: c++ boost boost-program-options


    【解决方案1】:

    一个代码示例真的很有帮助。

    但是,既然你的结构将包含向量,为什么不绑定那个向量呢?

    简单示例:

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

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

    【讨论】:

    • 非常感谢您提供的代码 sn-p。绑定向量应该有助于我的情况。当我们提供诸如./test --item=a --item=b 之类的输入时,这会起作用吗?
    • ...是的。这正是我所做的......你看到现场样本了吗?
    • 如果您不知道,--item={a,b,c}bash 中的大括号扩展并扩展为 --item=a --item=b --item=c
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 2019-04-16
    • 2015-12-13
    • 2016-02-22
    相关资源
    最近更新 更多