c++ - 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
我的问题是:
为什么在or的情况下
decltype(k)
anddecltype(v)
不是引用类型?for(auto & [k,v]:m)
for(auto && [k,v]:m)
为什么
decltype(k)
是类型const
的情况下for(auto [k,v]:m)
?
解决方案
问题 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
。
推荐阅读
- python - 如何从回归模型进行预测?
- flutter - Dart:将地图转换为 2 个列表
- node.js - Stripe API(节点) - 无法获取客户列表
- python - 从烧瓶返回不符合预期
- neo4j - Neo4J中如何更改多个节点的相同属性?
- python - 安装并运行 Mac Python Open CV
- python - 为什么我收到 TypeError: unsupported operand type(s) for /: 'str' and 'int'?
- flutter - 有没有办法在 Flutter 中的文本内绘制?
- java - 努力使用 Java (Jsoup) 处理 web scape 数据
- css - 仅适用于 Iphone 6 的媒体查询