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;
    }

    结果:

  • 相关阅读:
    数据加密算法详解
    自定义标签+阻尼动画+圆角图片+titleBar随滑动渐隐和显示
    Android MVP Plugin,一键完成MVP结构代码编写
    jquery-validate校验
    C# 后台获取请求来源、文件下载
    【通用邮件发送】C# QQ 网易邮箱
    【asp.net mvc】 扩展 htmlhelper 实现分页
    在MVC5中使用Ninject 依赖注入
    c# txt 文件上传、写入TXT文件、创建图形验证码
    uploadify图片上传配置
  • 原文地址:https://www.cnblogs.com/yifengs/p/15180674.html
Copyright © 2011-2022 走看看