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日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改