gpt4 book ai didi

c++ - std::hash 模板特化的前向声明

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:00 26 4
gpt4 key购买 nike

为什么前向声明如下:

template<typename T> struct std::hash;

用 gcc 和 clang 编译失败,但用 Visual Studio 2015 编译?

gcc 6.1.0(使用 coliru):

main.cpp:11:34: error: invalid use of template-name 'std::hash' without an argument list
template<typename T> struct std::hash;
^~~~

clang 3.8.0(使用 coliru):

main.cpp:11:29: error: forward declaration of struct cannot have a nested name specifier
template<typename T> struct std::hash;
^~~~~

它在 VS ( http://webcompiler.cloudapp.net/ ) 下工作。哪个编译器是正确的?

顺便说一句。 C++ Primer 第 5 版中使用了相同的声明。好吧 - 它使用的几乎相同 class而不是 struct : template <class T> class std::hash;这是错误的。

完整代码:

#include <unordered_map>

/*
// compiles with gcc,clang,VS
namespace std {
template<typename T>
struct hash;
}*/

// Compiles only with VS
template<typename T> struct std::hash;

struct MyData {
MyData() {}
MyData(int d1, int d2) : data1(d1), data2(d2) {}
bool operator==(const MyData& rop) const {
return rop.data1 == data1 && rop.data2 == data2;
}

friend struct std::hash<MyData>;
private:
int data1;
int data2;
};

namespace std {
template<>
struct hash<MyData> {
typedef MyData argument_type;
typedef size_t result_type;
size_t operator()(const argument_type& data) const noexcept;
};

size_t hash<MyData>::operator()(const argument_type& data) const noexcept {
return hash<unsigned>()(data.data1) ^ hash<unsigned>()(data.data2);
}
}

int main() {
std::unordered_map<MyData, std::string> mm;
mm[MyData(1,1)] = "test1";
mm[MyData(2,2)] = "test1";
}

最佳答案

原因似乎主要是因为前向声明必须像常规声明一样发挥作用。即封装在 namespace 中,没有前缀。我想这将允许相同的解析器用于有意义的声明和前向声明。

关于c++ - std::hash 模板特化的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38797781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com