You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:30:05