简体   繁体   English

结构化绑定在C ++ 17中引入的标识符类型有哪些?

[英]What are the types of identifiers introduced by structured bindings in C++17?

To my knowledge, identifiers introduced by structured bindings in C++17 are in fact references to some "hidden" variable. 据我所知,C ++ 17中结构化绑定引入的标识符实际上是对某些“隐藏”变量的引用。 Such that 这样

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

is kind-of equivalent to 一种等同于

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

However, if I print out std::is_reference<decltype(a)>::value , I get 0 in the first case 1 in the second. 然而,如果打印出std::is_reference<decltype(a)>::value ,我得到0在第一种情况1中的第二个。 Why is that? 这是为什么?

if I print out std::is_reference<decltype(a)>::value , I get 0 in the first case 1 in the second. 如果我打印出std::is_reference<decltype(a)>::value ,我在第二种情况下的第一种情况下得到0。

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? 为什么即使我们可以证明ab引用元组中的元素并且可以通过它们修改这些值?
I'm not a language lawyer, but probably it is due to this bullet of the standard (working draft): 我不是语言律师,但可能是因为这个标准(工作草案)的子弹

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 如果e是一个未加括号的id-expression,命名一个结构化绑定[...],则decltype(e)是结构化绑定声明规范中给出的引用类型


Side note. 边注。 You should use this form to do so that a and b refer to the elements in the tuple: 您应该使用此表单来执行ab引用元组中的元素:

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;
}

See it on Coliru . 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 . 是更好地解释它,比人类的标准更容易理解一点的文章。

To my knowledge, identifiers introduced by structured bindings in C++17 are in fact references to some "hidden" variable. 据我所知,C ++ 17中结构化绑定引入的标识符实际上是对某些“隐藏”变量的引用。

If by "reference" you mean the language construct reference, this isn't quite correct. 如果通过“引用”表示语言构造引用,则这不完全正确。 The specifiers in the declaration appertain to the "hidden variable" you speak of. 声明中的说明符与您所说的“隐藏变量”有关。 The reference qualifier is optional. 参考限定符是可选的。 The code you presented would be more like this: 您提供的代码更像是这样的:

const auto& e = std::make_tuple(1, 2);
using E = remove_reference_t<decltype((e))>;
std::tuple_element<0, E>::type& a = get<0>(e);
std::tuple_element<1, E>::type& b = get<1>(e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM