std::remove_if与循环使用问题:无法调用FuncType输出字符串
问题原因及解决方法
核心问题
- 函数对象未执行调用:循环里的
ev.second;只是引用了函数对象,但没有触发调用操作,函数体的输出逻辑自然不会执行。 - 函数签名不匹配:你定义的
FuncType是std::function<void(std::string&)>,但通过std::bind绑定tes系列函数后,生成的函数对象不需要接收参数(因为已经固定了实参),这和FuncType要求的签名冲突,属于未定义行为,即使强行调用也可能出现异常。
修正方案
步骤1:修正函数类型定义
把FuncType改成无参的函数类型,匹配绑定后的函数对象签名:
using FuncType = std::function<void()>;
步骤2:正确调用函数对象
在循环中将ev.second;改为调用形式,触发函数执行:
ev.second();
完整修正代码
#include <iostream> #include <list> #include <functional> using namespace std; void tes(std::string s) { cout << "tes " << s << '\n'; } void tes2(std::string s) { cout << "tes " << s << '\n'; } void tes3(std::string s) { cout << "tes " << s << '\n'; } int main() { using FuncType = std::function<void()>; std::list<std::pair<int, FuncType>> events = { {1, std::bind(tes, "1")}, {2, std::bind(tes2, "2")}, {3, std::bind(tes3, "3")} }; int t = 1; auto remove_func = [&t](std::pair<int, FuncType> pair) -> bool { return pair.first == t; }; events.remove_if(remove_func); for (auto ev : events) { std::cout << ev.first << ' ' ; ev.second(); } }
拓展场景:如果需要动态传参
要是你原本想让函数对象接收外部传入的参数,而非通过std::bind固定实参,可以调整绑定方式,保留FuncType的原有签名:
// 绑定使用占位符,不固定实参 std::list<std::pair<int, FuncType>> events = { {1, std::bind(tes, std::placeholders::_1)}, {2, std::bind(tes2, std::placeholders::_1)}, {3, std::bind(tes3, std::placeholders::_1)} }; // 调用时传入目标字符串 ev.second("自定义参数");
内容的提问来源于stack exchange,提问作者lie ardi
相关产品推荐
相关产品推荐

