c++ - unordered_map 中带有模板类的 C2535(Microsoft Visual Studio 2015 CTP6)

标签 c++ hash unordered-map visual-studio-2015

我在尝试编译以下代码时遇到了一个奇怪的 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/

相关文章:

c++ - 节点句柄与 std::unique_ptr

c++ - 如果在 map 中找不到键,则返回其他值

c++ - 错误 c2338 C++ 标准不提供此类型的散列

c++ - 无法在C++中打开头文件

c++ - 知道为什么这个用户定义的文字会失败吗?

android - 我应该在哪里散列用户密码?

c# - 多次比较字符串

c++ - 我在哪里可以找到世界上最快的 atof 实现?

C++ 'vector' 未在此范围内声明

ruby-on-rails - 使用 Oj.dump 序列化时将符号转换为字符串