real pointers(真正的指針)做得很好的一件事是支持 implicit conversions(隱式轉換)。derived class pointers(派生類指針)隱式轉換到 base class pointers(基類指針),pointers to non-const objects(指向非常量對象的指針)轉換到 pointers to const objects(指向常量對象的指針),等等。例如,考慮在一個 three-level hierarchy(三層繼續體系)中能發生的一些轉換:
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(用戶定義智能指針類)中模擬這些轉換是需要技巧的。我們要讓下面的代碼能夠編譯:
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 的創建,而且我們當然不希望為了做到這一點而必須改變 SmartPtr template。
大體上,我們需要的 constructors(構造函數)的數量是無限的。因為一個 template(模板)能被實例化而產生無數個函數,所以似乎我們不需要為 SmartPtr 提供一個 constructor function(構造函數函數),我們需要一個 constructor template(構造函數模板)。這樣的 templates(模板)是 member function templates(成員函數模板)(經常被恰如其分地稱為 member templates(成員模板))——生成一個 class 的 member functions(成員函數)的 templates(模板)的范例:
template<typename T> class SmartPtr { public: template<typename U> // member template SmartPtr(const SmartPtr<U>& other); // for a "generalized ... // copy constructor" }; 這就是說對于每一種類型 T 和每一種類型 U,都能從一個 SmartPtr<U> 創建出一個 SmartPtr<T>,因為 SmartPtr<T> 有一個取得一個 SmartPtr<U> 參數的 constructor(構造函數)。像這樣的 constructor(構造函數)——從一個類型是同一個 template(模板)的不同實例化的 object 創建另一個 object 的 constructor(構造函數)(例如,從一個 SmartPtr<U> 創建一個 SmartPtr<T>)——有時被稱為 generalized copy constructors(泛型化拷貝構造函數)。