如何将成员函数指针传递给父类?C++回调问题排查
问题解决:子类成员函数作为父类回调的正确实现
先明确你代码里的核心问题,再给出修正方案:
1. 父类std::map的key类型非法
std::map<const string&, Callback>的写法错误,map的key必须是可拷贝构造的类型,引用类型无法满足这个要求,需要改为std::string。
2. std::bind用法错误
绑定成员函数时,必须显式指定成员函数的地址(&specificHandler::callback1),同时要保留原函数的两个参数占位符(std::placeholders::_1和std::placeholders::_2),否则绑定后的函数签名无法匹配std::function<void(const string&, const string&)>的要求。
修正后的完整代码
父类handler:
#include <string> #include <map> #include <functional> class handler { public: handler(){} using Callback = std::function<void(const std::string&, const std::string&)>; void AddTopicCallbackPair(const std::string& _st, Callback _cb) { m_callbackDictionary.insert(std::make_pair(_st, _cb)); } private: // 修正key类型为std::string std::map<std::string, Callback> m_callbackDictionary; };
子类specificHandler:
class specificHandler : public handler { public: specificHandler() { // 正确绑定成员函数,保留参数占位符 AddTopicCallbackPair("/root/dev/", std::bind(&specificHandler::callback1, this, std::placeholders::_1, std::placeholders::_2)); } void callback1(const std::string& _topic, const std::string& _jsonData) { // 实现你的回调逻辑 } void callback2(const std::string& _topic, const std::string& _jsonData) { // 实现你的回调逻辑 } private: };
更简洁的替代方案:Lambda表达式
相比std::bind,Lambda写法更直观,不容易出错:
specificHandler() { AddTopicCallbackPair("/root/dev/", [this](const std::string& _topic, const std::string& _jsonData) { callback1(_topic, _jsonData); }); }
关于你尝试的成员函数指针模板方案
你尝试的模板成员函数指针写法失败,是因为子类的成员函数指针不能直接转换为父类的成员函数指针,即使存在继承关系。这种场景下,用std::function配合绑定(bind或lambda)是最简便安全的实现方式。
内容的提问来源于stack exchange,提问作者Ori Tsachi
相关产品推荐
相关产品推荐

