gpt4 book ai didi

c++ - 让 boost 程序选项在函数作用域后持续存在

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:44 26 4
gpt4 key购买 nike

我有一个函数,它接受一个 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)

最佳答案

您应该更改 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?了解更多详情。

关于c++ - 让 boost 程序选项在函数作用域后持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47019727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com