广告位联系
返回顶部

C++ 通用类型 Any 的实现与核心思想

C语言 来源:互联网 作者:佚名 发布时间:2026-11-15 19:32:54 人浏览
摘要

1. 为什么需要 Any? C++ 是强类型语言,普通变量类型在编译期就确定了。 但有些场景需要保存任意类型的数据,例如: 协议上下文:一个连接可能处理 HTTP、WebSocket 等不同协议,需要保存不同

1. 为什么需要 Any?

C++ 是强类型语言,普通变量类型在编译期就确定了。
但有些场景需要保存任意类型的数据,例如:

  • 协议上下文:一个连接可能处理 HTTP、WebSocket 等不同协议,需要保存不同的上下文对象。
  • 配置项:值可能是 int、std::string、double 等。
  • 消息传递:不同消息携带不同类型的数据。

C 语言可以用 void*,但 void* 丢失了类型信息,不安全。
C++17 提供了 std::any,Boost 提供了 boost::any。
我们也可以自己实现一个 Any,核心思想就是 类型擦除(Type Erasure)。

2. 代码总览

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

#include <iostream>

#include <typeinfo>

#include <cassert>

#include <string>

 

class Any {

private:

    class holder {

    public:

        virtual ~holder() {}

        virtual const std::type_info& type() = 0;

        virtual holder* clone() = 0;

    };

 

    template<class T>

    class placeholder : public holder {

    public:

        placeholder(const T& val) : _val(val) {}

 

        virtual const std::type_info& type() { return typeid(T); }

        virtual holder* clone() { return new placeholder(_val); }

 

    public:

        T _val;

    };

 

    holder* _content;

 

public:

    Any() : _content(NULL) {}

 

    template<class T>

    Any(const T& val) : _content(new placeholder<T>(val)) {}

 

    Any(const Any& other)

        : _content(other._content ? other._content->clone() : NULL) {}

 

    ~Any() { delete _content; }

 

    Any& swap(Any& other) {

        std::swap(_content, other._content);

        return *this;

    }

 

    template<class T>

    T* get() {

        assert(typeid(T) == _content->type());

        return &((placeholder<T>*)_content)->_val;

    }

 

    template<class T>

    Any& operator=(const T& val) {

        Any(val).swap(*this);

        return *this;

    }

 

    Any& operator=(const Any& other) {

        Any(other).swap(*this);

        return *this;

    }

};

 

int main() {

    Any a;

    a = 10;

    int* pa = a.get<int>();

    std::cout << *pa << std::endl;

 

    a = std::string("nihao");

    std::string* ps = a.get<std::string>();

    std::cout << *ps << std::endl;

 

    return 0;

}

3. 核心思想:类型擦除

Any 要保存任意类型,但不能是模板类。
因为如果 Any 是模板类,使用时必须写成 Any<int>、Any<std::string>,就失去了“通用容器”的意义。

解决方案:

  • 定义一个非模板基类 holder,提供统一接口。
  • 定义一个模板子类 placeholder<T>,真正保存 T 类型的数据。
  • Any 内部只保存 holder* 指针,通过虚函数调用子类实现。

结构如下:

1

2

3

4

5

Any

 └── holder* _content

      ├── placeholder<int>         { int _val; }

      ├── placeholder<std::string> { std::string _val; }

      └── ...

这就是经典的 类型擦除:对外是统一的 Any,对内通过多态保存具体类型。

4. 模块拆解

4.1 holder 基类

1

2

3

4

5

6

class holder {

public:

    virtual ~holder() {}

    virtual const std::type_info& type() = 0;

    virtual holder* clone() = 0;

};

  • virtual ~holder():必须虚析构。
    因为 Any 析构时是 delete _content;,_content 是 holder*。
    如果析构函数不是虚函数,只会调用 holder 的析构,不会调用 placeholder<T> 的析构,导致资源泄漏。
  • type():返回真实类型信息,用于 get 时检查类型。
  • clone():克隆自身,返回一个新的 holder*。
    用于 Any 的拷贝构造,实现深拷贝。

4.2 placeholder 模板子类

1

2

3

4

5

6

7

8

9

10

11

template<class T>

class placeholder : public holder {

public:

    placeholder(const T& val) : _val(val) {}

 

    virtual const std::type_info& type() { return typeid(T); }

    virtual holder* clone() { return new placeholder(_val); }

 

public:

    T _val;

};

  • 构造函数参数必须是 const T&。
    如果写成 T&,当传入临时量(如 a = 10)时会报错:
    binding reference of type ‘int&’ to ‘const int’ discards qualifiers。
  • type() 返回 typeid(T),记录真实类型。
  • clone() 返回 new placeholder(_val),调用拷贝构造,生成一份新对象。
  • _val 是真正保存的数据。

4.3 Any 类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

class Any {

private:

    holder* _content;

public:

    Any() : _content(NULL) {}

 

    template<class T>

    Any(const T& val) : _content(new placeholder<T>(val)) {}

 

    Any(const Any& other)

        : _content(other._content ? other._content->clone() : NULL) {}

 

    ~Any() { delete _content; }

 

    Any& swap(Any& other) {

        std::swap(_content, other._content);

        return *this;

    }

 

    template<class T>

    T* get() {

        assert(typeid(T) == _content->type());

        return &((placeholder<T>*)_content)->_val;

    }

 

    template<class T>

    Any& operator=(const T& val) {

        Any(val).swap(*this);

        return *this;

    }

 

    Any& operator=(const Any& other) {

        Any(other).swap(*this);

        return *this;

    }

};

  • _content:指向实际保存数据的 holder 子类对象。
  • 默认构造:_content = NULL,表示空 Any。
  • 模板构造:根据 T 创建对应的 placeholder<T>。
  • 拷贝构造:调用 clone() 深拷贝。
  • 析构:delete _content,虚析构保证正确释放。
  • swap:交换两个 Any 的内部指针,效率高且异常安全。
  • get<T>():检查类型后返回数据指针。
  • operator=:使用 copy-and-swap 惯用法。

5. 关键流程

5.1 构造

1

2

3

Any a;              // _content = NULL

Any b(10);          // new placeholder<int>(10)

Any c(std::string("hello")); // new placeholder<std::string>("hello")

5.2 拷贝

1

Any d(b);           // d._content = b._content->clone()

clone() 会 new placeholder<int>(_val),所以 d 和 b 各自拥有一份数据,互不影响。

5.3 析构

1

~Any() { delete _content; }

因为 holder 有虚析构,所以 delete _content 会正确调用 placeholder<T> 的析构函数,释放 _val。

5.4 赋值:copy-and-swap

1

2

3

4

5

template<class T>

Any& operator=(const T& val) {

    Any(val).swap(*this);

    return *this;

}

步骤:

  1. 用 val 构造一个临时 Any 对象。
  2. 临时对象与 *this 交换 _content。
  3. 临时对象析构,释放原来 *this 保存的数据。

好处:

  • 异常安全:如果构造临时对象失败,*this 不受影响。
  • 代码简洁:拷贝赋值和模板赋值共用同一逻辑。

5.5 get:类型安全访问

1

2

3

4

5

template<class T>

T* get() {

    assert(typeid(T) == _content->type());

    return &((placeholder<T>*)_content)->_val;

}

  • assert 在 Debug 下检查类型是否匹配。
  • 类型匹配后,把 holder* 强制转换为 placeholder<T>*,返回 _val 的地址。
  • 注意:Release 下 assert 失效,如果类型不匹配会出错。生产环境建议抛异常或返回 nullptr。

6. 使用示例

1

2

3

4

5

6

7

8

9

10

11

12

int main() {

    Any a;

    a = 10;

    int* pa = a.get<int>();

    std::cout << *pa << std::endl;  // 10

 

    a = std::string("nihao");

    std::string* ps = a.get<std::string>();

    std::cout << *ps << std::endl;  // nihao

 

    return 0;

}

输出:

10
nihao


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • C++ 通用类型 Any 的实现与核心思想
    1. 为什么需要 Any? C++ 是强类型语言,普通变量类型在编译期就确定了。 但有些场景需要保存任意类型的数据,例如: 协议上下文:一个连
  • C++ 智能指针的所有权与使用的实现

    C++ 智能指针的所有权与使用的实现
    在前面实现容器时,我们已经多次遇到了谁申请、谁释放的情况。到了实际程序里,创建对象和使用对象往往发生在不同函数中:函数可以
  • C++ 栈展开机制(Stack Unwinding)的实现
    栈展开(Stack Unwinding)是理解 C++ 异常处理、RAII 资源管理、Linux 调用栈回溯、程序崩溃诊断以及编译器运行时机制的重要基础。 一、栈展开
  • C语言标准库之<ctype.h> 详解与深度解析
    在 C 语言开发中,字符处理是一个非常基础但非常重要的模块。无论是解析用户输入、分析文本文件、还是处理网络协议,字符的分类和转
  • Conan配置目标架构的详细教程
    conan install 是如何指定目标架构(如 arm64、x86_64) Conan 通过settings控制目标架构,不是靠命令行传参数,而是靠 profile 或直接在命令中用--
  • C++非类型模板参数之编译期常量与高性能编程的
    项目概述:从黑盒到白盒的模板参数进化 在C++模板编程的世界里,我们最熟悉的莫过于类型模板参数。每次写templatetypename T或者templateclas
  • C++从编译期多态到可变参数模板
    项目概述:为什么我们需要深入理解模板 如果你写过一段时间的C++,尤其是接触过标准库(STL),那么模板这个词对你来说一定不陌生。
  • C++日志库log4cpp实战介绍
    项目概述:为什么我们需要一个专业的日志库? 在C++项目里,尤其是那些需要长期运行的服务端程序或者复杂的桌面应用,调试和问题追踪
  • C#代码实现设置Word表格的列宽
    设置 Word 表格的列宽对于提升文档的可读性和整体美观度至关重要。合理的列宽能够避免文本过长导致阅读困难,尤其是在内容较多的表格
  • C++中的引用传参和指针传参的区别介绍
    核心概念对比 概念 C++ 前端 (JS/TS) 值传递 默认方式,完整拷贝 基本类型 (number, string等) 引用传递 需显式使用 或指针 对象、数组、函数等引
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计