我正在尝试使用 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)
类型为const
在for(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/