#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
ifx
is a prvaluetype&
ifx
is a lvaluetype&&
ifx
is a xvalue
因此有decltype(i)
== int&&
;而decltype((i))
== int&
,因此推断出i
是左值