Boost C++ 库

……是世界上最受推崇、设计最精湛的 C++ 库项目之一。 Herb SutterAndrei Alexandrescu, C++ Coding Standards

第 38 章 Boost.TypeErasure - Boost C++ 函数库
PrevUpHomeNext

第 38 章 Boost.TypeErasure

Steven Watanabe

根据 Boost 软件许可证版本 1.0 发布。(参见随附文件 LICENSE_1_0.txt 或在 https://boost.ac.cn/LICENSE_1_0.txt 复制)

目录

介绍
如何阅读本文档
基本用法
组合概念
多参数函数
深入概念
定义自定义概念
重载
概念映射
关联类型
使用 Any
构造
转换
参考文献
语法限制
示例
多态范围格式化器
类型安全的 printf
具有多个签名的 Boost.Function
概念定义
预定义概念
参考
头文件 <boost/type_erasure/any.hpp>
头文件 <boost/type_erasure/any_cast.hpp>
头文件 <boost/type_erasure/binding.hpp>
头文件 <boost/type_erasure/binding_of.hpp>
头文件 <boost/type_erasure/builtin.hpp>
头文件 <boost/type_erasure/call.hpp>
头文件 <boost/type_erasure/callable.hpp>
头文件 <boost/type_erasure/check_match.hpp>
头文件 <boost/type_erasure/concept_interface.hpp>
头文件 <boost/type_erasure/concept_of.hpp>
头文件 <boost/type_erasure/config.hpp>
头文件 <boost/type_erasure/constructible.hpp>
头文件 <boost/type_erasure/deduced.hpp>
头文件 <boost/type_erasure/derived.hpp>
头文件 <boost/type_erasure/dynamic_any_cast.hpp>
头文件 <boost/type_erasure/dynamic_binding.hpp>
头文件 <boost/type_erasure/exception.hpp>
头文件 <boost/type_erasure/free.hpp>
头文件 <boost/type_erasure/is_empty.hpp>
头文件 <boost/type_erasure/is_placeholder.hpp>
头文件 <boost/type_erasure/is_subconcept.hpp>
头文件 <boost/type_erasure/iterator.hpp>
头文件 <boost/type_erasure/member.hpp>
头文件 <boost/type_erasure/operators.hpp>
头文件 <boost/type_erasure/param.hpp>
头文件 <boost/type_erasure/placeholder.hpp>
头文件 <boost/type_erasure/placeholder_of.hpp>
头文件 <boost/type_erasure/rebind_any.hpp>
头文件 <boost/type_erasure/register_binding.hpp>
头文件 <boost/type_erasure/relaxed.hpp>
头文件 <boost/type_erasure/require_match.hpp>
头文件 <boost/type_erasure/same_type.hpp>
头文件 <boost/type_erasure/static_binding.hpp>
头文件 <boost/type_erasure/tuple.hpp>
头文件 <boost/type_erasure/typeid_of.hpp>
基本原理
为什么我必须显式指定析构函数的存在?
为什么是非成员函数?
为什么占位符的名称是 _a_b 而不是 _1 _2
为什么不使用 boost::ref 来表示引用?
未来工作
致谢
相关工作

Boost.TypeErasure 库在 C++ 中提供了比核心语言更灵活的运行时多态。

C++ 有两种截然不同的多态形式:虚函数和模板,它们各有优缺点。

  • 虚函数直到运行时才解析,而模板始终在编译时解析。如果你的类型可以在运行时变化(例如,如果它们依赖于用户输入),那么使用模板的静态多态将无济于事。
  • 虚函数可以与分离编译一起使用。模板的体必须在它被使用的每个翻译单元中可用,这会减慢编译速度并增加重新编译的次数。
  • 虚函数会自动明确参数的要求。模板仅在实例化时进行检查,这需要在测试、断言和文档中额外的工作。
  • 编译器会在每次实例化时为每个函数模板创建一个新的副本。这允许更好的优化,因为编译器可以静态地知道所有信息,但它也会导致二进制文件大小显著增加。
  • 模板支持值语义。易于推理的“表现像 int”且不共享的对象。另一方面,使用虚函数必须使用(智能)指针或引用。
  • 模板库可以允许第三方类型以非侵入式的方式进行适配,以实现无缝互操作。对于虚函数,您必须创建一个继承自基类的包装器。
  • 模板可以处理涉及多种类型的约束。例如,std::for_each 接受一个迭代器范围和一个可以对该范围内的元素进行调用的函数。虚函数实际上无法表达此类约束。

Boost.TypeErasure 库结合了模板卓越的抽象能力和虚函数的运行时灵活性。

Boost 包含这种多态的几种特殊情况:

  • boost::any 用于 CopyConstructible 类型。
  • boost::function 用于可以像函数一样调用的对象。
  • Boost.Range 提供了 any_iterator

Boost.TypeErasure 将其泛化,以支持任意需求,并提供了一套预定义的常用概念


PrevUpHomeNext