c++ - 为什么在定义默认值时 boost::program_options 抛出有关必需参数的错误

标签 c++ boost boost-program-options

这是我的代码:

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

int main(int argc, char *argv[]) {
    po::options_description cli_opts_desc("General flags");
    cli_opts_desc.add_options()
        ("help,h", po::value<std::string>()->default_value("all"), "Show this help message.")
    ;
    po::variables_map flags;
    po::store(po::parse_command_line(argc, argv, cli_opts_desc), flags);
    if (flags.count("help")) {
        std::cout << "flags['help'] is " << flags["help"].as<std::string>() << std::endl;
        if (flags["help"].as<std::string>() != "all") std::cout << "specific description for "
                                                              << flags["help"].as<std::string>() << std::endl;//todo
        else std::cout << cli_opts_desc << std::endl;
    } else {
        std::cout << "no --help provided" << std::endl;
    }
}

或者更确切地说,它的简化版本。当我运行时

./test

它按预期显示了帮助消息。但是,如果我运行

./test --help #or
./test -h

然后它抛出一个错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::invalid_command_line_syntax> >'
  what():  the required argument for option '--help' is missing
Aborted

即使我声明了默认值,我也不明白为什么会发生这种情况。

是什么导致了这个错误?我该如何解决?

注意:如果可能的话,我想避免使用implicit_value;在现实世界中,这并不局限于我的 --help,并且能够为短选项指定带有空格的参数是一件很好的小事,可以避免愚蠢的错误。

最佳答案

试试这个:

("help,h", "Show this help message.")

没有参数,但没有提供参数时没有提示。

关于c++ - 为什么在定义默认值时 boost::program_options 抛出有关必需参数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617045/

相关文章:

CMake 上的 Boost_DIR-NOTFOUND

c++ - cURL 是一个网络库吗?

c++ - 我可以用 boost.program_options 做什么和不能做什么?

c++ - boost 序列化和 std::shared_ptr

c++ - Boost.Program_options - 免费值(没有选项的值)

c++ - 升压:bad_any_cast: failed conversion using boost:any_cast error

c++ - 如何让我的程序监视 C++ 中的文件修改?

c++ - 如何使用非静态相机跟踪任何移动物体? [Opencv]

c++ - 在 C++ 中静态构造函数的实现不起作用

c++ - 将 wstring 转换为 string 的古代代码中的可怕警告