我在尝试编译以下代码时遇到了一个奇怪的 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 Express 中编译时没有出现任何问题。
问题:这是 VS 2015 的错误还是这种行为在某种程度上符合标准?
最佳答案
实际上,这是由于 §14.5.1/4 中的一个微妙之处而导致格式错误的:
In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration (7.1.6.3).
并且,根据 §20.9/2,hash
声明为
Header
<functional>
synopsis// 20.9.12, hash function primary template: template <class T> struct hash;
因此尝试
template <int NUMBER>
struct hash<Container<NUMBER>> { /*…*/ };
相反。
关于c++ - unordered_map 中带有模板类的 C2535(Microsoft Visual Studio 2015 CTP6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29864305/