首页 > 解决方案 > unordered_map 结构化绑定中的推导类型

问题描述

我试图通过使用 和 来查看 unordered_map 的结构化绑定中的auto推导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)or for(auto & [k,v]:m)or for(auto && [k,v]:m),输出总是

1
1

我的问题是:

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

解决方案


问题 1) 就像这里指定的一样

1) 如果参数是命名结构化绑定的无括号 id 表达式,则 decltype 产生引用的类型(在结构化绑定声明的规范中描述)。

这里:

情况 2:绑定类似元组的类型 [...] 第 i 个标识符的引用类型是std::tuple_element<i, E>::type.

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

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

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


推荐阅读