为什么 boost::p rogram_options 在定义默认值时会抛出有关必需参数的错误

Why does boost::program_options throw an error about a required argument when the default is defined

本文关键字:错误 参数 rogram boost options 默认值 定义 为什么      更新时间:2023-10-16

这是我的代码:

#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.")
没有参数

,但没有提供参数时没有投诉。