C++核心准则T.13:对于简单的,单类型参数概念,使用缩略记法更好

时间:2022-07-24
本文章向大家介绍C++核心准则T.13:对于简单的,单类型参数概念,使用缩略记法更好,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

月季

T.13: Prefer the shorthand notation for simple, single-type argument concepts

T.13:对于简单的,单类型参数概念,使用缩略记法更好

Reason(原因)

Readability. Direct expression of an idea.

可读性。直接表现想法。

Example (using TS concepts)示例(使用TS概念)

To say "T is Sortable":

为了表达“T是可排序类型”:

template<typename T>       // Correct but verbose: "The parameter is
//    requires Sortable<T>   // of type T which is the name of a type
void sort(T&);             // that is Sortable"

template<Sortable T>       // Better (assuming support for concepts): "The parameter is of type T
void sort(T&);             // which is Sortable"

void sort(Sortable&);      // Best (assuming support for concepts): "The parameter is Sortable"

The shorter versions better match the way we speak. Note that many templates don't need to use the template keyword.

较短的版本更符合我们想要表达的。注意很多模板不需要使用模板关键字。

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 a compiler that supports concepts (e.g., GCC 6.1 or later), you can remove the //

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

Enforcement(实施建议)

  • Not feasible in the short term when people convert from the <typename T> and <class T> notation.
  • 如果人们从<typename T> 和<class T>记法转过来,使用缩略记法是不合适的。
  • Later, flag declarations that first introduce a typename and then constrain it with a simple, single-type-argument concept.
  • 随后,标记第一次引入类型名并马上使用简单的,单类型概念对其进行约束的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t13-prefer-the-shorthand-notation-for-simple-single-type-argument-concepts