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

Boost Asio开发报错:boost::enable_shared_from_this<TCP_Connection>模板未定义

解决Boost Asio中enable_shared_from_this模板未定义的错误

你遇到的Implicit instantiation of undefined template 'boost::enable_shared_from_this<TCP_Connection>'错误,核心原因是编译器找不到boost::enable_shared_from_this模板的定义——尽管你包含了<boost/asio.hpp>,但这个头文件并不会自动引入enable_shared_from_this的相关定义。

解决方案

  • 显式添加<boost/enable_shared_from_this.hpp>头文件,这是enable_shared_from_this模板的定义所在。
  • 同时显式包含<boost/shared_ptr.hpp>,确保boost::shared_ptr的定义被正确引入(部分场景下可能被间接包含,但显式引入能避免依赖问题)。

修改后的代码示例

#pragma once

#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>  // 新增:引入enable_shared_from_this模板定义
#include <boost/shared_ptr.hpp>                // 新增:引入shared_ptr定义
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <array>

using boost::asio::ip::tcp;

class TCP_Connection : public boost::enable_shared_from_this<TCP_Connection> {
public:
    typedef boost::shared_ptr<TCP_Connection> pointer;

    static pointer create(boost::asio::io_context &ioc);
    tcp::socket& socket();
    void start();
private:
    explicit TCP_Connection(boost::asio::io_context &ioc);
    void handleWrite();

    tcp::socket _socket;
    std::string _message;
};

额外说明

不同Boost版本的头文件依赖可能略有差异,但enable_shared_from_this.hpp的位置在绝大多数版本中保持一致。显式包含必要头文件是避免此类编译错误的可靠做法,不要依赖其他头文件的间接引入。

内容的提问来源于stack exchange,提问作者dolor3sh4ze

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:01:23