您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“C++中為什么不要模板化類繼承”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“C++中為什么不要模板化類繼承”吧!
T.80:不要天真地模板化類繼承
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<typename T>
struct Container { // an interface
virtual T* get(int i);
virtual T* first();
virtual T* next();
virtual void sort();
};
template<typename T>
class Vector : public Container<T> {
public:
// ...
};
Vector<int> vi;
Vector<string> 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<int>::sort() is called, so it must generate code for it. Similar for vector<string>::sort(). Unless those two functions are called that's code bloat. Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
編輯器接受這段代碼時(shí),無法知道vector<int>::sort()是否被調(diào)用了,因此必須為之生成代碼。vector<string>::sort()的情況也一樣。只要這兩個(gè)函數(shù)沒有被調(diào)用,這就是一種代碼膨脹。想象一下:這種情況如果發(fā)生在一個(gè)包含數(shù)十個(gè)成員函數(shù)和被多次例示的數(shù)十個(gè)派生類的繼承結(jié)構(gòu)時(shí)會(huì)發(fā)生什么。
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í)施建議)
標(biāo)記依賴模板參數(shù)的虛函數(shù)。
到此,相信大家對(duì)“C++中為什么不要模板化類繼承”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。