前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.3:使用模板表现容器和范围

C++核心准则T.3:使用模板表现容器和范围

作者头像
面向对象思考
发布2020-08-27 15:51:40
2320
发布2020-08-27 15:51:40
举报

蜀葵

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(示例)

代码语言:javascript
复制
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(反面示例)
代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 蜀葵
  • T.3: Use templates to express containers and ranges
  • Reason(原因)
    • Example, bad(反面示例)
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档