c++ - unordered_map 结构化绑定(bind)中的推导类型

标签 c++ c++17 structured-bindings

我正在尝试使用 auto 查看 unordered_map 的结构化绑定(bind)中推导的类型, auto &auto && .

#include <string>
#include <iostream>
#include <unordered_map>
#include <type_traits>

int main() {   

    std::unordered_map<std::string, std::string> m{{"a","a1"}, {"b","b1"}};

    for(auto &&  [k,v]:m)
    {
        std::cout << std::is_same<decltype(k), std::string const  >::value << '\n';
        std::cout << std::is_same<decltype(v), std::string >::value << '\n';

    }
}

不管我用for(auto [k,v]:m)for(auto & [k,v]:m)for(auto && [k,v]:m) ,输出始终为

1
1

我的问题是:

  • 为什么 decltype(k)decltype(v)for(auto & [k,v]:m) 的情况下不是引用类型或for(auto && [k,v]:m)

  • 为什么 decltype(k)类型为constfor(auto [k,v]:m) 的情况下?

最佳答案

问题1) 如指定here

1) If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type (described in the specification of the structured binding declaration).

here :

Case 2: binding a tuple-like type [...] The referenced type for the i-th identifier is std::tuple_element<i, E>::type.

一个std::pair (参见问题 2 的答案)实际上是 2 的元组。因此它是“元组类似”。

因此,在这种情况下,Key 和 T 的基本类型总是被返回(产生)。

问题2) 内部 unordered_map 分配为std::pair<const Key, T> 。因此,k 为 const .

关于c++ - unordered_map 结构化绑定(bind)中的推导类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58720213/

相关文章:

c++17 通过生成预先声明的类型列表的笛卡尔积来制作 std::variant

c++ - 如何在宏中正确转发结构化绑定(bind)参数

c++ - 如何在头文件中声明相同类类型的数组?

c++ - SFML 环境中缺少 OpenGL 函数

c++ - 为什么 Xcode 11 beta 不能使用 C++17 的 <filesystem> header ?

c++ - std::reference_wrapper 的大小有任何保证吗?

c++ - 我应该使用哪种数据类型?

c++ - 如何禁用特定的未知 #pragma 警告(GCC 和/或 Clang)

c++ - 为什么绑定(bind)到引用类型时 "const auto [x, y]"的行为不符合预期?

c++ - 结构化绑定(bind)中的 const 引用是否会延长分解对象的生命周期?