获取升级程序选项以在功能范围之后保留

时间:2017-10-30 16:10:58

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

我有一个函数,它接受boost::program_options::options_description,添加一些选项,然后返回该东西。看起来好像我的选项在函数范围结束后没有持久化,我的选项就消失了。我如何让他们坚持下去?

#include <boost/program_options.hpp>
#include <utility>


void generic_args(boost::program_options::options_description desc, boost::program_options::positional_options_description p) {
    desc.add_options()
        ("input", boost::program_options::value<std::vector<std::string>>(), "input files")
        ("help,h", "produce help message")
        ("verbose,v", "put the pretty words and numbers on the light screen");

    p.add("input", -1);
}

int main(int argc, const char** argv) {
    boost::program_options::options_description desc("Allowed options");
    boost::program_options::positional_options_description p;
    generic_args(desc, p);
    boost::program_options::variables_map parameters;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(p).run(), parameters);
    boost::program_options::notify(parameters);
    return 0;
}

这是输出:

scott@beast:~/test/test_args$ g++ -std=c++11 main.cpp -o a.out -lboost_program_options
scott@beast:~/test/test_args$ ./a.out
scott@beast:~/test/test_args$ ./a.out --help
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::unknown_option> >'
  what():  unrecognised option '--help'
Aborted (core dumped)

1 个答案:

答案 0 :(得分:1)

您应该更改generic_args以参考参数:

void generic_args(boost::program_options::options_description &desc,
                  boost::program_options::positional_options_description &p)
{
  // ...
}

目前generic_args修改descp副本(它们按价值传递)。

请查看Does C++ pass objects by value or reference?What's the difference between passing by reference vs. passing by value?了解详情。