C++使用std::function/std::bind传递智能指针为函数参数编译报错求解
错误原因
核心错误是std::enable_shared_from_this的模板参数使用不符合要求:
std::enable_shared_from_this是CRTP(奇异递归模板模式)工具类,要求模板参数必须是继承它的当前类本身的类型- 你当前代码中
Connection类继承时传递的是类的模板参数T,当实例化Connection<int>时,相当于继承了std::enable_shared_from_this<int>,内部维护的弱指针类型为std::weak_ptr<int> - 当调用
std::make_shared<Connection<int>>构造对象时,内部会尝试将Connection<int>*类型的指针赋值给std::weak_ptr<int>,类型不匹配直接触发编译错误。
修复方案
仅需要修改Connection类的继承声明,将std::enable_shared_from_this的模板参数替换为Connection<T>即可:
// 修改前 // template <typename T> // class Connection : public std::enable_shared_from_this<T> // 修改后 template <typename T> class Connection : public std::enable_shared_from_this<Connection<T>>
修复后完整可运行代码
#include <functional> #include <iostream> #include <memory> template <typename T> struct Message { T a; }; template <typename T> class Connection : public std::enable_shared_from_this<Connection<T>> { typedef std::function<void(Message<T>&)> msg_handle; public: void SetHandle(msg_handle handle) { handle_ = handle; } void Run() { Message<T> t; std::cout << "Run() from Connection" << std::endl; handle_(t); } private: msg_handle handle_; }; template <typename T> class Server { public: void OnMessage(Message<T>& msg, std::shared_ptr<Connection<T>> remote) { std::cout << "OnMessage() from Server" << std::endl; } }; int main() { std::shared_ptr<Server<int>> server = std::make_shared<Server<int>>(); std::shared_ptr<Connection<int>> connection = std::make_shared<Connection<int>>(); connection->SetHandle(std::bind(&Server<int>::OnMessage, server, std::placeholders::_1, connection)); connection->Run(); return 0; }
运行输出
Run() from Connection OnMessage() from Server
内容的提问来源于stack exchange,提问作者Nikita Pavlenko
相关产品推荐
相关产品推荐

