结构化绑定:当某物看起来像参考并且行为类似于参考,但不是参考时 [英] structured bindings: when something looks like a reference and behaves similarly to a reference, but it's not a reference

查看:70
本文介绍了结构化绑定:当某物看起来像参考并且行为类似于参考,但不是参考时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我见过

Yesterday I've seen an interesting question here on SO about structured binding.
We can sum up it as it follows. Consider the example code below:

#include <tuple>
#include <type_traits>

int main() {
    auto tup = std::make_tuple(1, 2);
    auto & [ a, b ] = tup;
    // the following line won't compile for a isn't a reference
    // static_assert(std::is_reference_v<decltype(a)>);
}

在这种情况下,decltype(a)int(可能是由于此项目符号(工作草案):

In this case decltype(a) is int (probably) because of this bullet (working draft):

如果e是命名结构化绑定的非括号id表达式[...],则decltype(e)是结构化绑定声明的规范中给出的引用类型

if e is an unparenthesized id-expression naming a structured binding [...], decltype(e) is the referenced type as given in the specification of the structured binding declaration

此处是@Curious在感兴趣的评论中提供的wandbox的摘要.它表明实际上a不是参考,仅此而已.
到目前为止,对于最初的问题如此好,OP询问为什么它是int而不是int &,并且标准说看起来是可以接受的答案.

Here is a snippet on wandbox provided by @Curious in the comments for those that are interested. It shows that actually a isn't a reference, nothing more.
So far so good for the original question, OP asked why it was int instead of int & and the standard says that looked like an acceptable answer.

无论如何,我想知道委员会为何如此决定.归根结底,a是指元组中的元素,我可以通过a修改该元素.换句话说,a的声明看起来像是引用中的一个,它的行为类似于引用,但不是引用.

Anyway, I'd like to know why the committee decided so. At the end of the day, a refers to an element in the tuple and I can modify that element through a. In other terms, the declaration of a looks like the one of a reference, it behaves similarly to a reference but it's not a reference.

我可以接受这一点,但是我想知道背后的原因是什么.为什么decltype(a)不能简单地是int &?亵渎者可以理解的有意义的原因吗?

I can live with this, but I'd like to know what are the reasons behind that. Why decltype(a) cannot be simply int &? Is there a meaningful reason that a profane can understand?

推荐答案

我昨天写了这个:

decltype(x),其中x是结构化绑定,将引用的名称命名为 该结构化绑定的类型.在类似元组的情况下,这是 std::tuple_element返回的类型,可能不是引用 即使结构化绑定本身实际上始终是 在这种情况下参考.这有效地模拟了 绑定到其非静态数据成员具有以下类型的结构 由tuple_element返回,具有绑定的参考性 本身只是一个实现细节.

decltype(x), where x is a structured binding, names the referenced type of that structured binding. In the tuple-like case, this is the type returned by std::tuple_element, which may not be a reference even though the structured binding itself is in fact always a reference in this case. This effectively emulates the behavior of binding to a struct whose non-static data members have the types returned by tuple_element, with the referenceness of the binding itself being a mere implementation detail.

这篇关于结构化绑定:当某物看起来像参考并且行为类似于参考,但不是参考时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆