【发布时间】:2017-09-16 08:48:12
【问题描述】:
我已经阅读了关于使用 cppreference 的 C++17 中 std::unordered_map 的推导指南。
然后尝试运行以下示例,该示例是从 cppreference 复制的。
#include <unordered_map>
int main() {
// std::unordered_map m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type
// cannot deduce pair<const Key, T> from
// {"foo", 1} or {"bar", 2}
std::unordered_map m1 = std::initializer_list<
std::pair<char const* const, int>>({{"foo", 2}, {"bar", 3}}); // guide #2
std::unordered_map m2(m1.begin(), m1.end()); // guide #1
}
但是,编译器给出了错误。
main.cpp: In function 'int main()':
main.cpp:7:84: error: class template argument deduction failed:
std::pair<char const* const, int>>({{"foo", 2}, {"bar", 3}}); // guide #2
^
main.cpp:7:84: error: no matching function for call to 'unordered_map(std::initializer_list<std::pair<const char* const, int> >)'
In file included from /usr/local/include/c++/7.2.0/unordered_map:48:0,
from main.cpp:1:
/usr/local/include/c++/7.2.0/bits/unordered_map.h:101:11: note: candidate: template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> unordered_map(std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>)-> std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>
class unordered_map
^~~~~~~~~~~~~
为什么编译器会报错?
【问题讨论】:
-
永远不要在地图中使用 char* 作为键。
-
@manni66: ...除非你真的知道你在做什么。
-
libstdc++ 尚未为其无序关联容器实现推导指南。 (而这些容器恰好是以阻止隐式指南工作的方式实现的。)
-
@manni66 演绎指南可以轻松将字符指针更改为
std::string...
标签: c++ g++ c++17 unordered-map template-argument-deduction