real pointers(真正的指針)做得很好的一件事是支持 implicit conversions(隱式轉(zhuǎn)換)。derived class pointers(派生類指針)隱式轉(zhuǎn)換到 base class pointers(基類指針),pointers to non-const objects(指向非常量對(duì)象的指針)轉(zhuǎn)換到 pointers to const objects(指向常量對(duì)象的指針),等等。例如,考慮在一個(gè) three-level hierarchy(三層繼續(xù)體系)中能發(fā)生的一些轉(zhuǎn)換:
class Top { ... }; class Middle: public Top { ... }; class Bottom: public Middle { ... }; Top *pt1 = new Middle; // convert Middle* => Top* Top *pt2 = new Bottom; // convert Bottom* => Top* const Top *pct2 = pt1; // convert Top* => const Top* 在 user-defined smart pointer classes(用戶定義智能指針類)中模擬這些轉(zhuǎn)換是需要技巧的。我們要讓下面的代碼能夠編譯:
template<typename T> class SmartPtr { public: // smart pointers are typically eXPlicit SmartPtr(T *realPtr); // initialized by built-in pointers ... };
class BelowBottom: public Bottom { ... }; 我們就需要支持從 SmartPtr<BelowBottom> objects 到 SmartPtr<Top> objects 的創(chuàng)建,而且我們當(dāng)然不希望為了做到這一點(diǎn)而必須改變 SmartPtr template。
大體上,我們需要的 constructors(構(gòu)造函數(shù))的數(shù)量是無(wú)限的。因?yàn)橐粋€(gè) template(模板)能被實(shí)例化而產(chǎn)生無(wú)數(shù)個(gè)函數(shù),所以似乎我們不需要為 SmartPtr 提供一個(gè) constructor function(構(gòu)造函數(shù)函數(shù)),我們需要一個(gè) constructor template(構(gòu)造函數(shù)模板)。這樣的 templates(模板)是 member function templates(成員函數(shù)模板)(經(jīng)常被恰如其分地稱為 member templates(成員模板))——生成一個(gè) class 的 member functions(成員函數(shù))的 templates(模板)的范例:
template<typename T> class SmartPtr { public: template<typename U> // member template SmartPtr(const SmartPtr<U>& other); // for a "generalized ... // copy constructor" }; 這就是說對(duì)于每一種類型 T 和每一種類型 U,都能從一個(gè) SmartPtr<U> 創(chuàng)建出一個(gè) SmartPtr<T>,因?yàn)?SmartPtr<T> 有一個(gè)取得一個(gè) SmartPtr<U> 參數(shù)的 constructor(構(gòu)造函數(shù))。像這樣的 constructor(構(gòu)造函數(shù))——從一個(gè)類型是同一個(gè) template(模板)的不同實(shí)例化的 object 創(chuàng)建另一個(gè) object 的 constructor(構(gòu)造函數(shù))(例如,從一個(gè) SmartPtr<U> 創(chuàng)建一個(gè) SmartPtr<T>)——有時(shí)被稱為 generalized copy constructors(泛型化拷貝構(gòu)造函數(shù))。