如何使用notifier()和composing()?

问题描述 投票:0回答:1

我有C ++代码,它使用以下方面的选项声明:

boost::program_options::option_descriptions::add_options()

我需要为正则表达式和其他检查添加每个选项值的检查。

我决定使用notifier()来达到这个目的。例如:

add_options()
("myoption", bpo::value<string>()->notifier(param_validator()), "My option description")
;

其中param_validator是功能对象,它验证选项值。

我有另一个选项,已经使用composing()例如:

("myoption2", bpo::value<string>()->composing(), "My option 2 description")

为同一选项调用notifier()的语法是什么?或者可以根据这个选项调用notifier()?

c++ boost options
1个回答
0
投票

composing成员有一个notifier成员。所以你只需要从notifier打电话给composing。工作范例:

#include<string>
#include<iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>
#include <iterator>

int main()
{
    using str_vect_type = std::vector<std::string>;
    size_t cmdcnt = 5;
    const char* cmdline[] = { "dmy.exe", "--myoption", "this_that", "--myoption2", "testing" };
    auto param_validator = [](const std::string& x) {std::cout << " " << x <<  "\nparam_validator\n"; };
    auto other = [](const str_vect_type& x) {for (auto& s : x)std::cout << " " << s << '\n'; std::cout << "the_other\n"; };
    po::variables_map vm;
    try {

        po::options_description desc("Allowed options");
        desc.add_options()
            ("myoption", po::value<std::string>()->notifier(param_validator), "My option description")
            ("myoption2", po::value<std::vector<std::string> >()->composing()->notifier(other), "My option 2 description")
            ;
        po::store(po::parse_command_line(cmdcnt, cmdline, desc), vm);
        //as if from ini file hack...
        const_cast<str_vect_type*>(&vm["myoption2"].as<str_vect_type>())->push_back("another");
        po::notify(vm);
    }
    catch (std::exception& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.