为什么std :: tuple会分解成右值引用?
#include <tuple> template <typename,typename> struct same_type; template <typename T> struct same_type<T,T> {}; void foo() { std::tuple tuple(1,'a',2.3,true); auto[i,c,d,b] = tuple; same_type<decltype(i),int &&>{}; same_type<decltype(c),char &&>{}; same_type<decltype(d),double &&>{}; same_type<decltype(b),bool &&>{}; }
使用gcc trunk编译时没有错误.
我本来期望普通的类型,例如
same_type<decltype(i),int>{};
解决方法
GCC错误.应用于结构化绑定的decltype返回引用的类型,对于类似于元组的情况,它是std :: tuple_element返回的确切类型.换句话说,语言在这里非常努力地隐藏这些实际上是引用的事实.
For an expression
e
,the type denoted bydecltype(e)
is defined as
follows:
- if
e
is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]),decltype(e)
is the referenced type as given in the
specification of the structured binding declaration;- […]
Otherwise,if the expression
std::tuple_size<E>::value
is a
well-formed integral constant expression […] Given the typeTi
designated bystd::tuple_element<i,E>::type
,eachvi
is a
variable of type “reference toTi
” initialized with the initializer,
where the reference is an lvalue reference if the initializer is an
lvalue and an rvalue reference otherwise; the referenced type isTi
.