加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么std :: tuple会分解成右值引用

发布时间:2020-12-16 03:33:14 所属栏目:百科 来源:网络整理
导读:为什么std :: tuple会分解成右值引用? #include tupletemplate typename,typename struct same_type;template typename T struct same_typeT,T {};void foo() { std::tuple tuple(1,'a',2.3,true); auto[i,c,d,b] = tuple; same_typedecltype(i),int {}; sa
为什么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>{};

Live example

解决方法

GCC错误.应用于结构化绑定的decltype返回引用的类型,对于类似于元组的情况,它是std :: tuple_element返回的确切类型.换句话说,语言在这里非常努力地隐藏这些实际上是引用的事实.

[dcl.type.simple]/4:

For an expression e,the type denoted by decltype(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;
  • […]

[dcl.struct.bind]/3:

Otherwise,if the expression std::tuple_size<E>::value is a
well-formed integral constant expression […] Given the type Ti
designated by std::tuple_element<i,E>::type,each vi is a
variable of type “reference to Ti” 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 is Ti.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读