C++备忘录105:decltype() vs decltype(())

本文探讨了C++中的decltype()和decltype(())的区别。decltype()用于获取变量或成员的声明类型,而decltype(())根据表达式类别返回实际类型。在特定情况下,decltype能揭示表达式的左值或右值特性,对于理解和使用C++类型系统至关重要。
摘要由CSDN通过智能技术生成
#include <type_traits>

void foo(int&& i) {
    static_assert(std::is_same_v<decltype(i), int&&>);
    static_assert(std::is_same_v<decltype((i)), int&>);
}

i类型是右值引用,但是本身的value catagory是左值。

但是直接decltype(i)的话,发现返回的永远是右值引用,没有任何它是左值的证明

这是因为decltype的特殊用法,当i是一个名字的时候,decltype()返回的是类型,而decltype(())返回的是value catagory,规则如下(C++ Template 2nd B.3)

If e is the name of an entity (such as variable, function, enumerator, or data member) or a class member access, decltype(e) yields the declared type of that entity or the denoted class member. Thus, decltype can be used to inspect the type of variable.

For any expression x, decltype((x)) yields:

  • type if x is a prvalue
  • type& if x is a lvalue
  • type&& if x is a xvalue

因此有decltype(i) == int&&;而decltype((i)) == int&,因此推断出i是左值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值