【问题标题】:Type of variables in structured binding结构化绑定中的变量类型
【发布时间】:2019-04-26 22:43:49
【问题描述】:
#include <type_traits>

int main()
{
    int arr[1] = { 6 };

    auto& ref1 = arr[0];  
    static_assert( std::is_same_v<decltype( ref1 ), int&> ); //ok

    auto& [ ref2 ] = arr;
    static_assert( std::is_same_v<decltype( ref2 ), int> ); //ok
    static_assert( std::is_same_v<decltype( ref2 ), int&> ); //error
}

在该示例中,标识符 ref1ref2 之间的区别是什么?据我了解,结构绑定中的ref2也有引用类型,但是为什么decltype为它指明了非引用类型呢?

【问题讨论】:

  • this 回答你的问题了吗?

标签: c++ c++17 auto decltype type-deduction


【解决方案1】:

decltype(e) 的行为会有所不同,具体取决于e 作为参数给出的内容。对于结构化绑定,decltype 产生以下内容,[dcl.type.simple]

对于表达式edecltype(e)表示的类型定义如下:

  • 如果e 是一个无括号的id-expression 命名结构化绑定,decltype(e)引用类型,如结构化绑定声明的规范中给出的

以数组类型表达式作为初始化器的结构化绑定声明的引用类型是元素[dcl.struct.bind]的类型:

如果E是元素类型为T的数组类型,则标识符列表中的元素数量应等于E的元素数量。每个 vi 是一个左值的名称,它引用数组的元素 i,其类型为T引用的类型是T。 [ 注意:T 的顶级 cv 限定符是 cv。 — 尾注 ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多