天天看點

C++核心準則T.24:使用标簽類或特征區分隻有語義不同的概念

T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.

T.24:使用标簽類或特征區分隻有語義不同的概念

Reason(原因)

Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.

兩個概念具有相同的文法需求但是語義不同會引起歧義,除非程式員可以區分它們。

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

template<typename I>    // iterator providing random access
concept bool RA_iter = ...;

template<typename I>    // iterator providing random access to contiguous data
concept bool Contiguous_iter =
    RA_iter<I> && is_contiguous<I>::value;  // using is_contiguous trait      

The programmer (in a library) must define is_contiguous (a trait) appropriately.

程式員(在庫代碼中)必須恰當地定義is_contiguous(特征)。

Wrapping a tag class into a concept leads to a simpler expression of this idea:

将一個标簽類封入概念可以更簡單地表現想法。

template<typename I> concept Contiguous = is_contiguous<I>::value;

template<typename I>
concept bool Contiguous_iter = RA_iter<I> && Contiguous<I>;      

The programmer (in a library) must define is_contiguous (a trait) appropriately.

程式員(在庫代碼中)必須恰當地定義is_contiguous(特征)。

Note(注意)

Traits can be trait classes or type traits. These can be user-defined or standard-library ones. Prefer the standard-library ones.

特征的表達可以通過特征類和類型特征給你來實作。它們可以是使用者定義的,也可以由标準庫提供。标準庫提供的方式更好。

Enforcement(實施建議)

  • The compiler flags ambiguous use of identical concepts.
  • 編譯器應該标記想定義完全相同的概念的混亂用法。
  • Flag the definition of identical concepts.
  • 标記完全相同的概念定義。

 原文連結

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t24-use-tag-classes-or-traits-to-differentiate-concepts-that-differ-only-in-semantics​​

新書介紹

​​《實戰Python設計模式》​​是作者最近出版的新書,拜托多多關注!

C++核心準則T.24:使用标簽類或特征區分隻有語義不同的概念

本書利用Python 的标準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟體開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。

對設計模式感興趣而且希望随學随用的讀者通過本書可以快速跨越從了解到運用的門檻;希望學習Python GUI 程式設計的讀者可以将本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、資料處理工作的讀者可以直接以本書中的示例為基礎,迅速建構自己的系統架構。

覺得本文有幫助?請分享給更多人。

關注微信公衆号【面向對象思考】輕松學習每一天!

面向對象開發,面向對象思考!

繼續閱讀