C++核心准则T.10:为所有的模板参数定义概念

面向对象思考

共 2506字,需浏览 6分钟

 ·

2020-08-24 00:18

石竹

T.10: Specify concepts for all template arguments

T.10:为所有的模板参数定义概念


Reason(原因)

Correctness and readability. The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template. A concept dramatically improves documentation and error handling for the template. Specifying concepts for template arguments is a powerful design tool.

正确性和可读性。一个模板参数的假定含义(语法和语义)是模板接口的基础。概念大幅度改善了模板的文档化和错误处理。为模板参数定义概念是一个强有力的设计工具。


Example(实例)

template
// requires Input_iterator
// && Equality_comparable, Val>
Iter find(Iter b, Iter e, Val v)
{
// ...
}

or equivalently and more succinctly:

或者使用下面功能等价但更简洁的方式:

template
// requires Equality_comparable, Val>
Iter find(Iter b, Iter e, Val v)
{
// ...
}
Note(注意)

"Concepts" are defined in an ISO Technical Specification: concepts. A draft of a set of standard-library concepts can be found in another ISO TS: ranges Concepts are supported in GCC 6.1 and later. Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only. If you use GCC 6.1 or later, you can uncomment them:

“概念”被ISO技术规格:concepts定义。一套标准库concepts的初步版本可以在另一个ISO技术规格:ranges中找到。GCC6.1以后都支持concepts。因此我们在实例代码中注释掉使用concepts的部分;也就是说我们只是将它们用作标准的注释。如果你使用GCC6.1之后的版本,可以打开注释。

template

    requires Input_iterator
&& Equality_comparable, Val>
Iter find(Iter b, Iter e, Val v)
{
// ...
}
Note(注意)

Plain typename (or auto) is the least constraining concept. It should be used only rarely when nothing more than "it's a type" can be assumed. This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.

直接的类型名(或auto)是最小约束的概念。它应该被极少使用,仅限于表现“它是一个类型”。这通常只在我们操作纯表达式树,延迟类型检查时有(作为模板元编程的一部分)存在的必要。

References: TC++PL4, Palo Alto TR, Sutton

参见:TC++PL4, Palo Alto TR, Sutton


Enforcement(实施建议)

Flag template type arguments without concepts

标记没有使用概念的模板类型参数。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t10-specify-concepts-for-all-template-arguments


新书介绍

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

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

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




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

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

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



浏览 44
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报