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; };