C++核心准则T.3:使用模板表现容器和范围
蜀葵
T.3: Use templates to express containers and ranges
T.3:使用模板表现容器和范围
Reason(原因)
Containers need an element type, and expressing that as a template argument is general, reusable, and type safe. It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
容器需要知道元素类型,将元素类型表示为模板参数是通行,可重用和类型安全的方式。它可以避免脆弱性和低效的变通。做为惯例,STL就是这么做的。
Example(示例)
template<typename T>
// requires Regular<T>
class Vector {
// ...
T* elem; // points to sz Ts
int sz;
};
Vector<double> v(10);
v[7] = 9.9;
Example, bad(反面示例)
class Container {
// ...
void* elem; // points to size elements of some type
int sz;
};
Container c(10, sizeof(double));
((double*) c.elem)[7] = 9.9;
This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
Hiding the void* behind macros simply obscures the problems and introduces new opportunities for confusion.
这段代码没有直接表达程序员的意图并对类型系统和优化器隐藏程序结构。用宏定义掩盖void*只会模糊化问题并进一步增加混淆的机会。
Exceptions: If you need an ABI-stable interface, you might have to provide a base implementation and express the (type-safe) template in terms of that. See Stable base.
例外:如果你需要ABI稳定的接口,你可能必须提供一个基础实现并按照其概念表现模板。
Enforcement(实施建议)
- Flag uses of void*s and casts outside low-level implementation code
- 标记使用void*并在外面的实现代码中使用低水平类型转换的情况。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t3-use-templates-to-express-containers-and-ranges
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 一句话ListenableFuture简介
- Google Guava Cache 使用
- Linux下安装maven3.6.2遇到的问题
- Unity3D网络通讯(五)--Socket通讯之Udp通讯
- IP不能作为rocketmq 的topic
- Unity3D网络通讯(六)-- UnityWebRequest实现WebService通讯
- Java Maven编译时没问题,运行时报java.lang.NoSuchMethodError
- 树莓派基础实验34:L298N模块驱动直流电机实验
- The consumer group[PushConsumer] has been created before, specify another name please
- 虚拟机系列 | JVM特点,基础结构与执行周期
- 报错 解决-bash: fork: retry: Resource temporarily unavailable
- 结构与算法(04):排序规则与查找算法
- 手把手教你在 TKE 集群中实现简单的蓝绿发布和灰度发布
- 虚拟机系列 | JVM类加载机制
- 树莓派综合项目2:智能小车(一)四轮驱动