您使用 Boost Program Options 的想法是使用多令牌/组合选项。
我们一起来
1)function1() - 定义所有可能的有效选项。添加
他们到一个option_description 对象。
auto function1() {
po::options_description desc;
for (auto opt : s_opts)
desc.add_options()(opt, po::value<std::string>());
desc.add_options()
("vector_of_string_option", po::value<VoS>()->multitoken()->composing(), "vector string")
;
return desc;
}
到目前为止一切顺利
2)function2() - 解析
配置文件并填充variable_map 对象。
auto function2(std::istream&& is) {
auto d = function1();
po::parsed_options parsed = po::parse_config_file(is, d, false);
po::variables_map vm;
po::store(parsed, vm);
po::notify(vm);
return vm;
}
仍然没有问题。
3)function3()-
返回一个选项的值。这个函数看起来像这样-
template <typename T>
T function3(std::string optName, po::variables_map const& vm) {
try {
return vm[optName].as<T>();
} catch (std::exception const& e) {
std::cerr << "Whoops: " << e.what() << "\n";
exit(1);
}
}
好的。
int main() {
auto vm = function2(std::istringstream(R"(
bar=BARRRR
# bar=QUXXXX # "cannot be specified more than once"
vector_of_string_option=value1
vector_of_string_option=value2
vector_of_string_option=value3
)"));
std::cout << function3<std::string>("bar", vm) << "\n";
for (auto& v : function3<VoS>("vector_of_string_option", vm)) {
std::cout << " - " << std::quoted(v) << "\n";
}
}
打印:
BARRRR
- "value1"
- "value2"
- "value3"
我希望返回的值是一个包含 3 个值的向量 - {"value1" , "value2" , "value3"}。
已经完成,请看Live On Coliru
由于 function3() 是类中的模板化函数,我无法为向量编写专门的函数(例如,使用 boost::split 拆分字符串)。
当然可以!你不能/部分/专攻,但你可以专攻:
template <>
VoS function3<VoS>(std::string optName, po::variables_map const& vm) {
try {
VoS result;
auto const& raw = vm[optName].as<VoS>();
using namespace boost::algorithm;
for(auto& rv : raw) {
VoS tmp;
split(tmp, rv, is_any_of(",; "), token_compress_on);
result.insert(result.end(), tmp.begin(), tmp.end());
}
return result;
} catch (std::exception const& e) {
std::cerr << "Whoops: " << e.what() << "\n";
exit(1);
}
}
这使得您可以使用多个值,但也可以拆分每个值:
int main() {
auto vm = function2(std::istringstream(R"(
bar=BARRRR
# bar=QUXXXX # "cannot be specified more than once"
vector_of_string_option=value1, value2, value3
vector_of_string_option=value4, value5, value6
)"));
std::cout << function3<std::string>("bar", vm) << "\n";
for (auto& v : function3<VoS>("vector_of_string_option", vm)) {
std::cout << " - " << std::quoted(v) << "\n";
}
}
打印
BARRRR
- "value1"
- "value2"
- "value3"
- "value4"
- "value5"
- "value6"
再看一遍Live On Coliru
红利
如果你想要部分特化,要么将function3 的实现委托给模板类,要么使用标签调度。这也使得解析成set<int> 或list<bool> 成为可能/容易。
草稿:http://coliru.stacked-crooked.com/a/7971dd671010d38e