首页 > 解决方案 > 如何使用 CLI11 检查选项是否是标志?

问题描述

我正在使用 CLI11 库(链接)来解析我的程序的命令行参数。

现在我想将有关我的程序选项的信息打印到标准输出。似乎通过添加的标志App::add_flag(...)也在内部存储为选项,但我需要在输出中区分它们。

如何确定哪个选项是标志?

这是一个简化的示例:

std::string file, bool myflag;
CLI::App *command = app.add_subcommand("start", "Start the program");

command->add_option("file", file, "This is a file option")->required();
command->add_flag("--myflag", myflag);

print_description(command);

...

std::string print_description(CLI::App* command) {
    for (const auto &option : command->get_options()) {
      result << R"(<option name=")" << option->get_name() << R"(" description=")" << option->get_description()
             << R"(" type=")";
      if (/*option is a flag*/) {
        result << "flag";
      } else {
        result << "option";
      }
      result << R"("/>)";
    }
    return result.str();
}

标签: c++command-line-arguments

解决方案


根据这个问题:https://github.com/CLIUtils/CLI11/issues/439,该函数Option::get_expected_min将始终返回 0 作为标志。所以可以像这样检查它:

if (option->get_expected_min() == 0) {
  result << "flag";
} else {
  result << "option";
}

推荐阅读