解决C++ unordered_map“nvalid use of incomplete type ‘struct std::hash“ 问题

转自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.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值