如何将notifier()与composed()一起使用?

时间:2019-01-21 09:15:59

标签: c++ boost options

我有C ++代码,该代码使用以下选项声明:

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

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

我决定为此目的使用notifier()。例如:

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

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

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

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

为同一选项调用notifier()的语法是什么? 或完全可以为此类选项调用notifier()吗?

1 个答案:

答案 0 :(得分: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;
}