我需要将 std::vector 的元素转换为基于模板参数的类型,并使用这些参数调用函数。在伪代码中:
template <typename T...>
void foo(std::vector<std::string> v) {
if (v.size() != sizeof...(T))
throw std::runtime_error("Bad");
bar(convert<T0>(v[0]), convert<T1>(v[1]), ..., convert<Tn>(v[n]));
}
我的问题是如何从参数包中获取元素索引,我认为使用折叠表达式会有某种技巧,但我无法弄清楚。
如果你知道一个向量中的元素个数等于参数包的大小,你可以通过增加一层间接来解决这个问题:
template<typename... T, std::size_t... is>
void foo_impl(const std::vector<std::string>& v, std::index_sequence<is...>) {
bar(convert<T>(v[is])...);
}
template<typename... T>
void foo(const std::vector<std::string>& v) {
assert(v.size() == sizeof...(T));
foo_impl<T...>(v, std::index_sequence_for<T...>{});
}
这里的想法是同时展开两个大小相同的包Ts...
和is...
。
C++20解决方案:
template<typename... T>
void foo(const std::vector<std::string>& v) {
assert(v.size() == sizeof...(T));
[&v]<std::size_t... is>(std::index_sequence<is...>) {
bar(convert<T>(v[is])...);
}(std::index_sequence_for<T...>{});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句