我现在拥有的是
("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 :
#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/