specialization of template… in different namespace解决方案
同样的代码,使用clang++编译通过,可是使用g++报错如下:
error: specialization of 'template<class _Tp> struct std::hash' in different namespace [-fpermissive] class std::hash<MyClassType>
源代码为:
template<>
class std::hash<MyClassType>
{ // hash functor
public:
//...Codes...
};
修改为:
namespace std{
template<>
class hash<MyClassType>
{ // hash functor
public:
//...Codes...
};
}
按照上面的改动就可以解决这个错误。看报错的原因,是说我声明的hash和系统预定义的hash不在同一个命名空间内。
在一些旧版的gcc中是可以接受这样的写法,但是这样是并不合法的。
这里的代码中的hash明明就是在std的命名空间。这个出错很奇怪,考虑可能是编译器的BUG。这个解决方案,也只是相同的代码逻辑换了一种写法而已。
参考链接:
- https://blog.csdn.net/coder_xia/article/details/6764777
- http://gcc.gnu.org/ml/gcc/2005-04/msg00134.html
- https://womble.decadent.org.uk/c++/template-faq.html#specialise-ns