decltype

decltype

查询表达式的类型

与using/typedef并用,用于定义类型

  1. 定义普通的类型(int,int*)using ptrdiff_t = decltype((int*)0 - (int*)0);using size_t = decltype(sizeof(0));
  2. 定义空指针类型using nullptr_t = decltype(nullptr);
  3. 定义迭代器类型vector<int >vec;typedef decltype(vec.begin()) vectype;vectype i =vec.begin();

重用匿名类型

在定义struct{}xxx;后,可用decltype(xxx) yyy;重命名该类型

结合auto声明返回类型

template <typename T>
auto multiply(T x, T y)->decltype(x*y)
{
	return x*y;
}

注意:为什么不在返回值直接声明 decltype()?
因为x和y变量还没有声明,用auto作为返回值占位,在函数定义声明x,y后再->decltype()声明返回类型

decltype推导规则

  • 如果e是一个没有带括号的标记符表达式或者类成员访问表达式,那么的decltype(e)就是e所命名的实体的类型。此外,如果e是一个被重载的函数,则会导致编译错误。
	decltype (arr) var1; //int 标记符表达式
 
    decltype (ptr) var2;//int *  标记符表达式
 
    decltype(s.d) var3;//doubel 成员访问表达式

*	decltype(Overloaded) var4;//重载函数。编译错误。
  • 否则 ,假设e的类型是T,如果e是一个将亡值,那么decltype(e)为T&&
decltype (RvalRef()) var5 = 1;
  • 否则,假设e的类型是T,如果e是一个左值,那么decltype(e)为T&。
	decltype ((i))var6 = i;     //int&
 
    decltype (true ? i : i) var7 = i; //int&  条件表达式返回左值。
 
    decltype (++i) var8 = i; //int&  ++i返回i的左值。
 
    decltype(arr[5]) var9 = i;//int&. []操作返回左值
 
    decltype(*ptr)var10 = i;//int& *操作返回左值
 
    decltype("hello")var11 = "hello"; 
    //const char(&)[9]  字符串字面常量为左值,且为const左值。
  • 否则,假设e的类型是T,则decltype(e)为T。
decltype(1) var12;//const int

decltype(Func(1)) var13=true;//const bool

decltype(i++) var14 = i;//int i++返回右值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值