C++ - 模板類模板成員函數(member function template)隱式處理(implicit)變化

來源:互聯網
上載者:User

標籤:

模板類模板成員函數(member function template)隱式處理(implicit)變化


本文地址: http://blog.csdn.net/caroline_wendy/article/details/24233693


指標支援隱式轉換(implicit conversion), 在動態綁定中,衍生類別指標能夠轉換為基類指標.

可是模板的執行個體化(instantiations)之間, 是單獨存在的, 

衍生類別的執行個體化的模板(SmartPtr<Derived>), 不能轉換為基類執行個體化的模板(SmartPtr<Base>);


須要明白的編寫, 由於衍生類別也能夠繼續做為基類, 產生衍生類別, 所以無法直接寫出建構函式.

使用成員函數模板(member function template), 再聲明一個模板參數, 提供這樣的隱式轉換.


為了使用轉換僅僅能發生在能夠轉換的指標, 如"Derived->Base", 不能逆序, 所以引入相關約束推斷能否夠轉換.

成員初始化列表(member initialization list)中調用get()函數, 推斷能否夠隱式轉換.


使用成員函數模板的建構函式, 是成員函數的一種, 並非重載複製建構函式, 所以類會自己主動產生一個預設建構函式.


代碼注意: 第一個能夠轉換, 第二個不能轉換, 第三個使用預設的建構函式.


代碼:

/* * test.cpp * *  Created on: 2014.04.20 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <iostream>using namespace std;class Base{};class Derived : public Base {};template<typename T>class SmartPtr {public:SmartPtr() = default;template<typename U>SmartPtr(const SmartPtr<U>& other): heldPtr(other.get()) {std::cout << "SmartPtr:CopyConstructor" << std::endl;}T* get() const {return heldPtr;}private:T* heldPtr;};int main() {SmartPtr<Derived> spd;SmartPtr<Base> spb(spd);//SmartPtr<Base> spb1;//SmartPtr<Derived> spd1(spb1); //無法進行隱藏轉換SmartPtr<Base> spd2;SmartPtr<Base> spd21(spd2); //使用預設的複製建構函式return 0;}

輸出:

SmartPtr:CopyConstructor





著作權聲明:本文部落格原創文章。部落格,未經同意,不得轉載。

C++ - 模板類模板成員函數(member function template)隱式處理(implicit)變化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.