C++ 类中模版函数具体化报错

学到了HashTable,于是自己打算写一个类 类中有静态函数 就是把 各种基础类型 传换成 32位 int

img

在网上查找过这个问题, 说在类外面写函数实现 , 好像也不管用 , 而且他这个 报错内容 英文意思 搞不清楚

C++标准要求显示特例化必须在命名空间里声明,下面引用C++03, §14.7.3/2:

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.
An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member.

你可以改为如下形式

#include <iostream>

class HashCode
{
    template <typename T>
    static int to_int32(const T &val) { return val; }
};

template <>
int HashCode::to_int32<float>(const float &val)
{
    return *((int *)(&val));
}

template <>
int HashCode::to_int32<double>(const double &val)
{
    long long *tmp = (long long *)(&val);
    return int((*tmp) ^ (*tmp) >> 32);
}

int main()
{
    return 0;
}

img


我这个没报错,估计是你的编译器错了不是gcc该是g++吧