C++核心准则T.42:使用模板别名简化记法并隐藏实现细节

面向对象思考

共 1872字,需浏览 4分钟

 · 2020-09-07

君子兰

T.42: Use template aliases to simplify notation and hide implementation details

T.42:使用模板别名简化记法并隐藏实现细节


Reason(原因)

Improved readability. Implementation hiding. Note that template aliases replace many uses of traits to compute a type. They can also be used to wrap a trait.

提高可读性。隐藏实现。注意模板别名代替很多用于计算类型特征的使用。它们可以用于封装特征。


Example(示例)

template
class Matrix {
// ...
using Iterator = typename std::vector::iterator;
// ...
};

This saves the user of Matrix from having to know that its elements are stored in a vector and also saves the user from repeatedly typing typename std::vector::.

Matrix的用户不必知道它的元素存存储于于vector,也让用户不必重复输入类型名std::vecttor::。


Example(示例)

template
void user(T& c)
{
// ...
typename container_traits::value_type x; // bad, verbose
// ...
}

template
using Value_type = typename container_traits::value_type;

This saves the user of Value_type from having to know the technique used to implement value_types.

Value_type的用户不必了解实现value_type的技术。

template
void user2(T& c)
{
// ...
Value_type x;
// ...
}
Note(注意)

A simple, common use could be expressed: "Wrap traits!"

简单,普通的用法可以被解释为“封装特征”。


Enforcement(实施建议)

  • Flag use of typename as a disambiguator outside using declarations. 

  • 标记在using外面将typename作为消歧器使用的情况。

  • ???


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t42-use-template-aliases-to-simplify-notation-and-hide-implementation-details


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



浏览 33
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报