温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么使用模板表现容器和范围

发布时间:2021-11-24 11:27:49 来源:亿速云 阅读:154 作者:iii 栏目:大数据

这篇文章主要介绍“C++怎么使用模板表现容器和范围”,在日常操作中,相信很多人在C++怎么使用模板表现容器和范围问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++怎么使用模板表现容器和范围”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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*并在外面的实现代码中使用低水平类型转换的情况。

到此,关于“C++怎么使用模板表现容器和范围”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI