C2535,其模板类位于无序映射中(Microsoft Visual Studio 2015 CTP6)

C2535 with template-class in unordered_map (Microsoft Visual Studio 2015 CTP6)

本文关键字:映射 Microsoft Visual CTP6 2015 Studio 无序 于无序 C2535      更新时间:2023-10-16

我在尝试编译以下代码时遇到一个奇怪的C2535编译器错误:

template<int NUMBER>
class Container {
public:
bool operator==(const Container& other) const { return true; }
};
namespace std {
template <int NUMBER>
class hash<Container<NUMBER>> {
public:
size_t operator()(const Container<NUMBER> & state) const {
return 0;
}
};
}
int main(int argc, char* argv[]){
auto* b = new std::unordered_map< Container<1>, int>(); //C2535
}

注意,如果我使用自己的基于模板的Hasher

template<int NUMBER>
class Hash {
public:
size_t operator()(const Container<NUMBER> & state) const {
return 0;
}
};
int main(int argc, char* argv[]){
auto* b = new std::unordered_map< Container<1>, int, Hash<1>>();
}

代码编译得很好。我还记得,在Visual Studio 2013学习版中,代码的编译没有遇到任何问题。

问题:这是VS 2015的错误吗?还是这种行为在某种程度上符合标准?

实际上,这是由§14.5.1/4:中的一个微妙之处造成的

重新声明中,部分专门化、显式专门化或类模板的显式实例化,类键应一致与原始类模板声明相同(7.1.6.3)。

并且,根据§20.9/2,hash被声明为

标题<functional>摘要

// 20.9.12, hash function primary template:
template <class T> struct hash;

因此尝试

template <int NUMBER>
struct hash<Container<NUMBER>> { /*…*/ };

相反。