我有一个函数,它接受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)
答案 0 :(得分:1)
您应该更改generic_args
以参考参数:
void generic_args(boost::program_options::options_description &desc,
boost::program_options::positional_options_description &p)
{
// ...
}
目前generic_args
修改desc
和p
的副本(它们按价值传递)。
请查看Does C++ pass objects by value or reference?和What's the difference between passing by reference vs. passing by value?了解详情。