如何解决当使用无序集时,为什么带有非常量运算符的哈希函子不能在Visual Studio中编译?
我将原来使我痛苦的代码简化为一个简单的示例:
带有伪相等运算符的类:
class MyClass {
public:
bool operator==(const MyClass& mc) {
return false;
}
};
然后是该类的虚拟哈希函子:
template<> struct std::hash<MyClass> {
size_t operator()(const MyClass& s) {
return 0;
}
};
和主要方法:
int main()
{
std::unordered_set<MyClass> set_1;
std::unordered_set<MyClass> set_2;
set_1 = set_2;
return 0;
}
在Visual Studio中,这会产生错误:
error C3848: expression having type 'const _Hasher' would lose some const-volatile qualifiers in order to call 'size_t std::hash<MyClass>::operator ()(const MyClass &)'
经过数小时的调试,我发现该错误的原因是非常量哈希函子,即,当我将签名更改为size_t operator()(const MyClass& s) const
但是,在GCC中,它不会产生任何错误(仅警告未使用的参数),而在Clang中,它只会产生警告:
warning: the specified hash functor does not provide a viable const call operator
我的问题是,为什么此代码无法在Visual Studio中编译?我知道拥有一个非常量哈希函子没有任何意义,但是我还没有找到不应该编译的任何理由。
此外,尽管VS在set_1
声明行上发出错误信号,但如果我从set_1
到set_2
删除赋值,代码可以正常编译。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。