C ++ 17中结构化绑定引入的标识符类型是什么? [英] What are the types of identifiers introduced by structured bindings in C++17?

查看:124
本文介绍了C ++ 17中结构化绑定引入的标识符类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,C ++ 17中结构化绑定引入的标识符实际上是对某些隐藏变量的引用。这样

To my knowledge, identifiers introduced by structured bindings in C++17 are in fact references to some "hidden" variable. Such that

auto [ a, b ] = std::make_tuple(1, 2);

等同于

auto e = std::make_tuple(1, 2);
auto& a = std::get<0>(e);
auto& b = std::get<1>(e);

但是,如果我打印出 std :: is_reference< decltype(a) > :: value ,在第一种情况下我得到 0 在第二种情况下是 1 。为什么?

However, if I print out std::is_reference<decltype(a)>::value, I get 0 in the first case 1 in the second. Why is that?

推荐答案


如果我打印出 std :: is_reference< ; decltype(a)> :: value ,在第一种情况下我得到0,在第二种情况下我得到1。

if I print out std::is_reference<decltype(a)>::value, I get 0 in the first case 1 in the second.

为什么即使我们可以证明 a b 是指元组中的元素,可以通过它们来修改这些值?

我不是语言律师,但可能是由于标准(工作草案)的项目符号

Why is that even if we can prove that a and b refer to the elements in the tuple and one can modify those values by means of them?
I'm not a language lawyer, but probably it is due to this bullet of the standard (working draft):


if 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






侧注。您应该使用这种形式来使 a b 引用元组中的元素:


Side note. You should use this form to do so that a and b refer to the elements in the tuple:

auto tup = std::make_tuple(1, 2);
auto & [ a, b ] = tup;

它遵循一个最小的有效示例:

It follows a minimal, working example:

#include <tuple>
#include <type_traits>
#include <iostream>

int main() {
    auto tup = std::make_tuple(1, 2);
    auto & [ a, b ] = tup;
    a = 0;
    std::cout << a << ", " << std::get<0>(tup) << std::endl;
}

请在 Coliru 。另一方面,您将使用以下表达式值的副本

See it on Coliru. On the other side, what you get is a copy of the values using the expression below:

auto [ a, b ] = std::make_tuple(1, 2);

此处是一篇说明得更好的文章,比人类的标准更易理解。

Here is an article that explains it better and is a bit more comprehensible than the standard for humans.

这篇关于C ++ 17中结构化绑定引入的标识符类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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