为什么要按如下方式进行前向声明:
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 第五版》中也使用了相同的声明。不过,在该书中使用了 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";
}
template<typename T> struct hash;
可以通过,但在VS中失败了。这就像gcc/clang不需要命名空间限定一样? - mike