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

 

转载于:https://www.cnblogs.com/creativityroom/p/6891772.html

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值