【发布时间】:2015-07-04 01:12:43
【问题描述】:
我在尝试编译以下代码时遇到一个奇怪的 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
}
请注意,如果我使用自己的基于模板的哈希器
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 的错误还是这种行为在某种程度上符合标准?
【问题讨论】:
-
std::hash 不是一个类。是结构。看直播rextester.com/VHHQE6270
-
@user2451677:据我所知,struct 只是一个默认访问是公共而不是私有的类。不管怎样,一个基于模板的 struct Hash 被完美编译了!
-
@user2451677 好点。我以为它被宣布为
class hash。 -
@user2451677:现在我明白你的意思了 :)
-
@Mischa,您是部分专业化模板。因此,它必须与主模板完全“相同”。 struct Hash 之所以有效,是因为它是新模板(主模板),而不是专业化
标签: c++ hash unordered-map visual-studio-2015