如何获取std::vector中存储的std::function函数调用返回值?
核心问题分析
- 模板与容器类型错误:
std::vector<P...>和std::initializer_list<P...>都是非法写法——std::vector和initializer_list仅支持存储单一类型,参数包P...展开后会试图让容器容纳多种类型,完全不符合容器的设计逻辑。 - 类型不匹配:typedef中指定的
std::function<void(my_type)>要求函数返回void,但传入的lambda实际返回string,类型直接冲突导致编译失败。 - 逻辑冗余:
execute_functions中return value;之后的std::cout << value;永远不会执行,属于无效代码。
解决方案
根据你的需求(存储多种类型可调用对象、调用时获取返回值),提供两种可行方案:
方案1:统一可调用对象签名(推荐,实现简单)
如果业务允许所有可调用对象使用统一签名,直接用单一类型的std::vector存储即可:
#include <iostream> #include <functional> #include <vector> #include <initializer_list> using namespace std; struct my_type { my_type(){} my_type(string _value) : value(_value) {} string value = "test"; string getValue(){return value;} }; // 模板仅需指定统一的可调用对象类型 template<typename Func> struct struct_name { struct_name(std::initializer_list<Func> list) : functions(list) {} std::vector<Func> functions; string value; my_type type; string execute_functions(){ value.clear(); for (auto& func : functions) { // 调用函数并获取返回值,可根据需求选择覆盖/拼接等逻辑 value = func(type); std::cout << value << endl; } return value; } }; // 统一签名:接收my_type参数,返回string using _functions = struct_name<std::function<string(my_type)>>; int main(int argc, char const *argv[]) { _functions object = { [](my_type var){ return var.getValue(); }, [](my_type var){ return var.getValue() + "_modified"; }, }; object.execute_functions(); return 0; }
方案2:存储多种类型可调用对象(使用std::variant)
如果必须存储不同签名的可调用对象(比如有的返回string、有的返回int),可以用std::variant封装多种类型,配合std::visit调用:
#include <iostream> #include <functional> #include <vector> #include <initializer_list> #include <variant> #include <string> using namespace std; struct my_type { my_type(){} my_type(string _value) : value(_value) {} string value = "test"; string getValue(){return value;} int getLength(){return value.size();} }; // 定义允许存储的可调用对象类型集合 using FuncVariant = std::variant< std::function<string(my_type)>, std::function<int(my_type)>, std::function<void(my_type)> >; struct struct_name { struct_name(std::initializer_list<FuncVariant> list) : functions(list) {} std::vector<FuncVariant> functions; my_type type; void execute_functions(){ for (auto& var_func : functions) { // 用std::visit处理不同类型的可调用对象 std::visit([this](auto&& func) { using ReturnType = decltype(func(this->type)); if constexpr (!std::is_void_v<ReturnType>) { auto result = func(this->type); // 根据返回值类型做对应处理 std::cout << "Result: "; if constexpr (std::is_same_v<ReturnType, string>) { std::cout << result << endl; } else if constexpr (std::is_same_v<ReturnType, int>) { std::cout << result << endl; } } else { func(this->type); // 无返回值的直接调用 } }, var_func); } } }; int main(int argc, char const *argv[]) { struct_name object = { [](my_type var){ return var.getValue(); }, [](my_type var){ return var.getLength(); }, [](my_type var){ cout << "Void function called: " << var.value << endl; } }; object.execute_functions(); return 0; }
内容的提问来源于stack exchange,提问作者lucky_pirate99
相关产品推荐
相关产品推荐

