boost::program_options:如何使用完整的选项名称和更多信息进行validation_error

boost::program_options: how to make validation_error with the full option name and more informative

本文关键字:信息 error validation 选项 options program 何使用 boost      更新时间:2023-10-16

当我使用boost::program_options时,抛出validation_error后,错误消息不会显示完整的选项名称。

我有以下用g++ -std=c++11 test.cpp -lboost_program_options编译的简单示例源代码。该程序有一个有效的命令行选项:--hello-world,应该设置为ab,例如./a.out --hello-world a有效,但./a.out --hello-world c无效。然后,执行带有无效选项的代码,例如./a.out --hello-world c。错误消息如下:

the argument for option 'world' is invalid

但我希望选项名称为hello-world,并且还应该显示无效值。我有什么办法可以改变这一点吗?

#include <boost/program_options.hpp>
int main(int argc, const char** argv)
{
    namespace po = boost::program_options;
    char v;
    po::options_description desc("Options");
    desc.add_options()
        ("hello-world", po::value<>(&v)->default_value('a')->notifier(
            [](char x)
            {
                if (x != 'a' && x != 'b')
                    throw po::validation_error(
                        po::validation_error::invalid_option_value,
                        "hello-world", std::string(1, x));
            }),
         "An option must be set to either 'a' or 'b'");
    try
    {
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv). options(desc).run(), vm);
        po::notify(vm);
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    return 0;
}

选项的名称是无效的"hello-world"。选项名称不能包含短划线"-"。

通常情况下,消息看起来像:

the argument ('32768') for option '--the_int16' is invalid