C++学习笔记之模版 remove_reference(引用移除)
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; };