Register__ 2022-02-07 21:42 采纳率: 89.5%
浏览 34
已结题

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

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

img

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

  • 写回答

2条回答 默认 最新

  • _GX_ 2022-02-07 22:27
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月15日
  • 已采纳回答 2月7日
  • 创建了问题 2月7日