普通指針支援隱式向上轉型(派生類指針 → 基類指針)。但智能指針 SmartPtr<Derived> 和 SmartPtr<Base> 是無關類型,無法隱式轉換。需通過成員函數模板實現「通用構造函數」。
templateclass shared_ptr { public: shared_ptr(const shared_ptr& r); // 顯式拷貝構造 template shared_ptr(const shared_ptr & r); // 通用構造 shared_ptr& operator=(const shared_ptr& r); // 顯式拷貝賦值 template shared_ptr& operator=(const shared_ptr & r); // 通用賦值 };
SmartPtr<Derived> → SmartPtr<Base>)。std::shared_ptr 等標準庫組件廣泛採用此模式。成員函數模板讓類模板不同實例間建立類似繼承的隱式轉換關係,同時保持類型安全。記住:提供通用構造/賦值時,必須同步提供普通拷貝構造/賦值。