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

    结果:

  • 相关阅读:
    CRC全套算法 CRC4,CRC5,CRC7,CRC8,CRC16,CRC32,CRC32 mpeg-2
    ubuntu18.04使用vscode报pylint is not install错误
    [转]C结构体之位域(位段/位域)
    获取gcc和clang的内置宏定义
    Win10下使用MinGW到指定路径编译C-C++文件
    【YM】ssh命令 远程登录Linux
    Linux环境下搭建Qt5.9开发环境
    WSL-Ubuntu-更换apt源为阿里源
    git常用命令
    Lucene的基本使用
  • 原文地址:https://www.cnblogs.com/yifengs/p/15180674.html
Copyright © 2011-2022 走看看