更新 最初的答案有错误的想法。这是更新。
因此,您希望 foo=(没有值)表现得好像该行甚至不在配置中一样。
这意味着默认值语义(即通知时发生的情况 - 将状态从解析器组件迁移到存储组件)不好。
您可以通过发明自己的值语义(可以说是 mybool_switch)和/或解决value<my_particulat_bool> 来解决它,您可以在其中添加流操作,以便选项按照您想要的方式运行。换句话说,就是用大炮打苍蝇。
但是,到目前为止,更简单的选择是在解析器阶段进行干预,在 notify() 之前更改 parsed_options。
这是一个带有现场演示的相当完整的插图:
Live On Coliru
#include <boost/program_options/config.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
namespace po = boost::program_options;
int main() {
po::options_description desc;
desc.add_options()
("foo", po::bool_switch())
("bar", po::bool_switch()->default_value(false))
("qux", po::bool_switch()->implicit_value(false))
;
std::set<std::string> const bool_switches {"foo", "bar", "qux" };
for (std::string contents :
{ "", "foo=", "foo=true",
"bar=", "bar=true",
"qux=", "qux=true"})
{
std::istringstream iss(contents);
po::parsed_options parsed = po::parse_config_file(iss, desc, false);
std::cout << "\n---\n" << std::quoted(contents) << "\n";
// the magic is here:
for (auto it = parsed.options.begin(); it!= parsed.options.end();) {
using V = std::vector<std::string>;
V const& v = it->value;
if (bool_switches.count(it->string_key) && (v==V{} || v==V{""})) {
std::cout << "*** Discarding config key without a value: " << it->string_key << "\n";
it = parsed.options.erase(it);
} else {
++it;
}
}
po::variables_map vm;
po::store(parsed, vm);
for (auto& key : bool_switches) {
auto& entry = vm[key];
std::cout << " " << key << " ->" << std::boolalpha
<< (entry.empty()?" .empty()":"")
<< (entry.defaulted()?" .defaulted()":"");
if (entry.empty())
std::cout << " (no value)\n";
else
std::cout << " value:" << entry.as<bool>() << "\n";
}
}
}
哪个会打印
---
""
bar -> .defaulted() value:false
foo -> .defaulted() value:false
qux -> .defaulted() value:false
---
"foo="
*** Discarding config key without a value: foo
bar -> .defaulted() value:false
foo -> .defaulted() value:false
qux -> .defaulted() value:false
---
"foo=true"
bar -> .defaulted() value:false
foo -> value:true
qux -> .defaulted() value:false
---
"bar="
*** Discarding config key without a value: bar
bar -> .defaulted() value:false
foo -> .defaulted() value:false
qux -> .defaulted() value:false
---
"bar=true"
bar -> value:true
foo -> .defaulted() value:false
qux -> .defaulted() value:false
---
"qux="
*** Discarding config key without a value: qux
bar -> .defaulted() value:false
foo -> .defaulted() value:false
qux -> .defaulted() value:false
---
"qux=true"
bar -> .defaulted() value:false
foo -> .defaulted() value:false
qux -> value:true