C++核心準則T.3:使用模板表現(xiàn)容器和范圍

蜀葵
T.3: Use templates to express containers and ranges
T.3:使用模板表現(xiàn)容器和范圍
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.
容器需要知道元素類型,將元素類型表示為模板參數(shù)是通行,可重用和類型安全的方式。它可以避免脆弱性和低效的變通。做為慣例,STL就是這么做的。
Example(示例)
template
// requires Regular
class Vector {
// ...
T* elem; // points to sz Ts
int sz;
};
Vector 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.
這段代碼沒有直接表達程序員的意圖并對類型系統(tǒng)和優(yōu)化器隱藏程序結(jié)構(gòu)。用宏定義掩蓋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穩(wěn)定的接口,你可能必須提供一個基礎(chǔ)實現(xiàn)并按照其概念表現(xiàn)模板。
Enforcement(實施建議)
Flag uses of?void*s and casts outside low-level implementation code
標記使用void*并在外面的實現(xiàn)代碼中使用低水平類型轉(zhuǎn)換的情況。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t3-use-templates-to-express-containers-and-ranges
新書介紹
《實戰(zhàn)Python設(shè)計模式》是作者最近出版的新書,拜托多多關(guān)注!

本書利用Python 的標準GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設(shè)計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設(shè)計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設(shè)計模式的利弊,并合理運用設(shè)計模式。
對設(shè)計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設(shè)計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
