如何基于可变模板参数将std::vector元素转换后调用可变参数函数
实现思路
核心是通过std::index_sequence生成和可变模板参数包长度一致的编译期下标序列,让类型参数和vector下标一一对应,再通过参数包展开完成转换和函数调用。
前置依赖实现示例
假设你已经有类型转换函数convert和目标函数bar,参考实现如下:
#include <vector> #include <string> #include <stdexcept> #include <utility> // 通用转换模板,可根据需求自定义特化 template <typename T> T convert(const std::string& s); template <> int convert<int>(const std::string& s) { return std::stoi(s); } template <> double convert<double>(const std::string& s) { return std::stod(s); } template <> std::string convert<std::string>(const std::string& s) { return s; } // 目标调用函数示例 void bar(int a, double b, const std::string& c) { // 自定义逻辑 }
C++20 最简实现(用泛型Lambda)
template <typename... Ts> void foo(std::vector<std::string> v) { if (v.size() != sizeof...(Ts)) { throw std::runtime_error("Bad"); } // 生成下标序列并绑定到类型参数包 [&]<std::size_t... Is>(std::index_sequence<Is...>) { bar(convert<Ts>(v[Is])...); }(std::make_index_sequence<sizeof...(Ts)>{}); }
C++17 兼容实现(用辅助函数)
如果不支持C++20泛型Lambda,可以把展开逻辑拆为独立辅助函数:
template <typename... Ts, std::size_t... Is> void call_bar(const std::vector<std::string>& v, std::index_sequence<Is...>) { bar(convert<Ts>(v[Is])...); } template <typename... Ts> void foo(std::vector<std::string> v) { if (v.size() != sizeof...(Ts)) { throw std::runtime_error("Bad"); } call_bar<Ts...>(v, std::make_index_sequence<sizeof...(Ts)>{}); }
使用示例
int main() { std::vector<std::string> input = {"1024", "2.718", "hello world"}; // 按模板参数顺序转换后调用bar foo<int, double, std::string>(input); return 0; }
内容的提问来源于stack exchange,提问作者cube
相关产品推荐
相关产品推荐

