C + + Learning Note template remove_reference (reference removal)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.