int Main () { int a[] = {1,2,3}; Decltype (*a) b = a[0]; a[04; // Output 4 return 0 ;}
The output is 4 because Decltype (*a) returns the type of *a, which is actually a int& we just want to have a way to get rid of this reference.
Try 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; // output 4, return 0 ;}
We introduced the class remove_reference to remove the reference, and during compilation, it was deduced that type T was int&,typedef t type, and that the type was actually a kind int&, so the result is still 4.
Try 2
Template <typename t>classremove_reference{ Public: typedef T type;}; Template<typename t>classRemove_reference<t&>{ Public: typedef T type;};intMain () {intA[] = {1,2,3}; Remove_reference<decltype (*a) >::type B = a[0]; a[0] =4; cout<< b;//Output 1 return 0;}
We are special to the template class, as a reference, when T is int&, the actual T in the class is int, the function of reference removal is completed.
So we found a way to achieve the mutual transformation between types t,t&,t*, as shown below
Template <typename t>classgettype{ 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 + + Learning Note template remove_reference (reference removal)