zoukankan      html  css  js  c++  java
  • 函数模板的局限性级解决方法(第三代具体化)

    1.

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person
    {
    public:
        Person(string name, int age)
        {
            this->m_Name = name;
            this->m_Age = age;
        }
        string m_Name;
        int m_Age;
    };
    template<class T>
    bool myCompare(T& a, T& b)
    {
        if (a == b)
        {
            return true;
        }
        return false;
    }
    void test01()
    {
        Person p1("Tom",10);
        Person p2("Jerry",20);
        int res = myCompare(p1, p2); //可以自行推导类型,但是无法判断
        cout << res << endl;
    }
    
    
    int main()
    {
        test01();
        system("Pause");
        return 0;
    }

    结果:

    解决方法

    模板不能解决所有的类型

    如果出现不能解决的类型,可以通过第三地具体化来解决问题

    template<> 返回值  函数名<具体类型>(参数) (返回值、函数名、参数等都必须和模板返回值保持一致)

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person
    {
    public:
        Person(string name, int age)
        {
            this->m_Name = name;
            this->m_Age = age;
        }
        string m_Name;
        int m_Age;
    };
    template<class T>
    bool myCompare(T& a, T& b)
    {
        if (a == b)
        {
            return true;
        }
        return false;
    }
    //通过第三代具体化自定义数据类型,解决不能做对比的问题
    //如果具体化能够优先匹配,那么就选择具体化
    //第三代具体化语法: template<> 返回值 函数名<具体类型>(参数...)
    template<> bool myCompare<Person>(Person& a, Person& b)
    {
        if (a.m_Age == b.m_Age)
        {
            return true;
        }
        return false;
    }
    void test01()
    {
        Person p1("Tom",10);
        Person p2("Jerry",10);
        int res = myCompare(p1, p2); //可以自行推导类型,但是无法判断
        cout << res << endl;
    }
    
    
    int main()
    {
        test01();
        system("Pause");
        return 0;
    }

    结果:

  • 相关阅读:
    延迟消失菜单
    控制产品上下滚动
    百度音乐全选
    百度文库评分两种代码写法
    选项卡
    搜狐视频
    m 调用传参图片切换
    IIS 7.5站点配置
    jquery plugins —— datatables 搜索后汇总
    jquery plugins —— datatables 增加行号
  • 原文地址:https://www.cnblogs.com/yifengs/p/15180674.html
Copyright © 2011-2022 走看看