转自https://blog.csdn.net/li459461891/article/details/104910925#commentBox
解决C++ unordered_map“nvalid use of incomplete type ‘struct std::hash“ 问题
Leon- 2020-03-16 23:00:31 842 已收藏 1
分类专栏: C++
版权
C++
专栏收录该内容
5 篇文章0 订阅
订阅专栏
问题
G++使用unordered_map时候,编译报错:invalid use of incomplete type ‘struct std::hash<,。。。,放在G++6.5交叉编译环境是OK的,但是放在ubuntu14.04报错。
解决&代码
既然G++早期版本不能自动生成枚举类型的hash模板类,那么手动添加template<> struct std::hash<...。
添加如下代码 #if ....#endif区域代码,即可解决问题。
#include <unordered_map>
#include <utility>
#include <cstdint>
#include <iostream>
#include <functional>
namespace test{
enum COLOR{ WHITE, BLAC };
}
#if 0 // 如果没有这里,G++4.8.4和G++5.4.0会报错
namespace std {
template<>
struct hash<test::COLOR> {
typedef test::COLOR argument_type;
typedef size_t result_type;
result_type operator () (const argument_type& x) const {
using type = typename std::underlying_type<argument_type>::type;
return std::hash<type>()(static_cast<type>(x));
}
};
}
#endif
namespace test{
class mytest{
public:
std::unordered_map<COLOR, int> id_map_;
};
}
int main(){
test::mytest t;
return 0;
}
结论
发现是G++的问题,ubuntu14.04默认是g++4.8.4,ubuntu16.04是g++5.4。
参考:https://stackoverflow.com/questions/48294401/error-invalid-use-of-incomplete-type-struct-stdhash
ubuntu14.04
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
ubuntu16.04
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.