gpt4 book ai didi

c++ - 结构化绑定(bind)的 decltype(auto) 是否应该是引用?

转载 作者:IT老高 更新时间:2023-10-28 12:51:45 24 4
gpt4 key购买 nike

考虑一个例子:

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

int main() {
auto tup = std::make_tuple(1, 2);
auto [ a, b ] = tup;
decltype(auto) e = a;
std::cout << std::boolalpha << std::is_reference_v<decltype(e)> << std::endl;
}

clang (输出:false)和 gcc (输出:true)在这个简单的情况下不同意。考虑到例如this Q&As e 应该是引用还是 gcc 错误?或者代码格式不正确?

最佳答案

标识符他们自己是引用。来自 [dcl.struct.bind]/3 :

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.

也就是说,ab都是int&& .

但是方式decltype(auto)实际行为来自[dcl.type.auto.deduct] :

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype.

这个措辞真的很尴尬,但归根结底:

decltype(auto) e = a;
~~~~~~~~~~~~~~

意思是:

decltype( a  ) e = a;
~~~~

decltype(a)表示,来自 [dcl.type.simple]/4.1 :

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;

a引用类型int , 所以 e必须是 int .这意味着它不是引用,并且 clang 是正确的。归档 81176 .

关于c++ - 结构化绑定(bind)的 decltype(auto) 是否应该是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com