C++學習筆記之模版 remove_reference(引用移除)

來源:互聯網
上載者:User

標籤:log   public   div   decltype   pointer   學習   pen   poi   template   

int main(){  int a[] = {1,2,3};  decltype(*a) b = a[0];  a[0] = 4;  cout << b; //輸出4  return 0;}

輸出為4,因為decltype(*a)返回*a的類型,實際上是一個int&,我們就想有沒有辦法去掉這個引用

嘗試1

template <typename T>class remove_reference{public:   typedef T type;};int main(){  int a[] = {1,2,3};  remove_reference<decltype(*a)>::type b = a[0];  a[0] = 4;  cout << b; //輸出4中,  return 0;}

我們引入了類remove_reference用於移除引用,在編譯期間,推匯出了類型T為int&,typedef T type中,type實際上就是類型int&,因此結果還是4

嘗試2

template <typename T>class remove_reference{public:   typedef T type;};template<typename T>class remove_reference<T&>{public:   typedef T type;};int main(){  int a[] = {1,2,3};  remove_reference<decltype(*a)>::type b = a[0];  a[0] = 4;  cout << b; //輸出1  return 0;}           

我們對模版類進行特化,特化為引用,當T為int&時,在類內實際的T為int,完成了引用移除的功能

 

因此我們找到了一種方法實作類別型T,T&,T*間的相互轉化,如下所示

template <typename T>class GetType{public:   typedef T type;   typedef T& type_ref;   typedef T* type_pointer;};template<typename T>class GetType<T&>{public:   typedef typename remove_reference<T>::type type;   typedef typename remove_reference<T>::type_ref type_ref;   typedef typename remove_reference<T>::type_pointer type_pointer;};template<typename T>class GetType<T*>{public:   typedef typename remove_reference<T>::type type;   typedef typename remove_reference<T>::type_ref type_ref;   typedef typename remove_reference<T>::type_pointer type_pointer;};

 

C++學習筆記之模版 remove_reference(引用移除)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.