簡體   English   中英

當定義默認值時,為什么boost :: program_options會引發有關必需參數的錯誤

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

這是我的代碼:

#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.")

沒有參數,但在沒有提供參數的情況下也不會抱怨。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM