c++ - boost::program_options bool_switch 使用多次

标签 c++ boost boost-program-options

我现在拥有的是

("someOption,s", po::bool_switch(&variable)->default_value(false), "")

我希望能够多次指定参数,并且每次出现都会切换此 bool 值。

示例:

default value = false

./program -s
value == true

./program -s -s
value == false

./program -s -s -s
value == true

有没有办法多次使用类似 bool_switch 的东西,以便重复打开/关闭?我需要自定义类型和验证器吗?

也许我可以以某种方式允许多次指定该选项,然后执行 vm.count("someOption") 并根据其值(偶数/奇数)切换我的变量。但我更愿意在选项描述 (add_options) 中指定该行为,而无需稍后检查和修改值。

最佳答案

我实际上花了 70 分钟尝试使用它来工作

  • composing()允许重复
  • vector 值虚拟选项 implicit_value({}, "")自定义通知程序(它们只运行一次)
  • 自定义notifier() - 无论选项出现和成功解析的频率如何,它们都只运行一次
  • variables_map 获取 vector 值选项的大小之后store/notify 。遗憾的是,大小始终为 1,大概是因为“组合”实际上并未在单个存储操作中组合(它仅在多次运行之间组合,因此选项的来源不同,那么?)。

可悲的结论是,似乎没有办法。在这里,我一贯的口头禅得到了证实:“简单胜过全知设计”,我建议做同样的事情,但使用 https://github.com/adishavit/argh :

Live On Coliru

#include "argh.h"
#include <iostream>

namespace {
    template <typename It>
    size_t size(std::pair<It, It> const& range) { return std::distance(range.first, range.second); }
}

int main(int argc, char** argv) {
    argh::parser p(argc, argv);

    auto num_s = size(p.flags().equal_range("s"));
    bool const variable = num_s % 2;
    std::cout << "Repeated: " << num_s << ", effective " << std::boolalpha << variable;

    std::cout << " (Command line was:";
    while (*argv) std::cout << " " << *argv++;
    std::cout << ")\n";
}

当使用各种命令行运行时,打印:

Repeated: 0, effective false (Command line was: ../build/sotest)
Repeated: 1, effective true (Command line was: ../build/sotest -s)
Repeated: 2, effective false (Command line was: ../build/sotest -s -s)
Repeated: 3, effective true (Command line was: ../build/sotest -s -s -s)
Repeated: 4, effective false (Command line was: ../build/sotest -s -s -s -s)
Repeated: 3, effective true (Command line was: ../build/sotest -s -s -s --other bogus)

关于c++ - boost::program_options bool_switch 使用多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723237/

相关文章:

c++ - 如何在 C/C++ 中创建数学曲线(可能只是图像)

c++ - 在网络上的两台机器之间传递消息

c++ - Boost:;program_options 1.49 - 无法与 -lboost_program_options 链接

c++ - 使用 boost program_options 进行动态配置

C++ 程序不会在返回时结束

c++ - 如何: Extend C++14 template function to variadic template,参数

c++ - 在不使用类的情况下隐藏可查询的程序状态?

c++ - 在这种情况下如何有效地使用 intrusive_ptr?

C++ boost asio : bind: Address already in use

c++ - 将 boost::program_options 分组到强制组中