C++核心準(zhǔn)則T.80:不要天真地模板化類繼承

T.80: Do not naively templatize a class hierarchy
T.80:不要天真地模板化類繼承
Reason(原因)
Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
模板化包含很多成員函數(shù),特別是虛函數(shù)的類繼承層次會(huì)導(dǎo)致代碼膨脹。
Example, bad(反面示例)
template
struct Container { // an interface
virtual T* get(int i);
virtual T* first();
virtual T* next();
virtual void sort();
};
template
class Vector : public Container {
public:
// ...
};
Vector vi;
Vector vs;
It is probably a bad idea to define a?sort?as a member function of a container, but it is not unheard of and it makes a good example of what not to do.
為容器定義一個(gè)排序成員函數(shù)幾乎肯定就是一個(gè)壞主意,但這并非沒有先例,可以當(dāng)作說明我們不應(yīng)該做什么的好例子。
Given this, the compiler cannot know if?vector
編輯器接受這段代碼時(shí),無法知道vector
Note(注意)
In many cases you can provide a stable interface by not parameterizing a base; see?"stable base"?and?OO and GP
在很多情況下,你可以在不必參數(shù)化基類的情況下提供穩(wěn)定的接口;參見“穩(wěn)定的基類和OO and?GP。
Enforcement(實(shí)施建議)
Flag virtual functions that depend on a template argument. ??? False positives
標(biāo)記依賴模板參數(shù)的虛函數(shù)。???假陽性。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t80-do-not-naively-templatize-a-class-hierarchy
新書介紹
《實(shí)戰(zhàn)Python設(shè)計(jì)模式》是作者最近出版的新書,拜托多多關(guān)注!

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