• C++模板template的使用


    模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数、返回值取得任意类型

    使用模板的目的就是能够让程序员编写与类型无关的代码。通常有两种形式:函数模板和类模板

    一、函数模板

    函数模板 针对仅参数类型不同的函数,使用函数模板可以使函数的功能不受参数类型的限制

    template<class T> 中的T可以被任意的数据类型替代,template是关键字,尖括号内的是模板形参列表,模板形参列表不能为空

    #include <iostream>
    #include <memory>
    using namespace std;
    template<class T>
    T GetMax(T a,T b)
    {
        return a>b?a:b;
    }
    int main() {
        cout<<GetMax(2,3)<<endl;
        cout<<GetMax(1.66,5.66)<<endl;
        cout<<GetMax('a','p')<<endl;
        cout<<GetMax("string","ss")<<endl;
        return 0;
    }

    二、类模板
    类模板 针对仅数据成员和成员函数类型不同的类。

    #include <iostream>
    #include<string>
    #include <memory>
    using namespace std;
    template<class T>
    class pclass
    {
    public:
        pclass()
        {
    
        };
        ~pclass()
        {
            cout<<"~pclass"<<endl;
        };
        T GetMax(T a, T b)
        {
            return a > b ? a : b;
        }
    private:
    
    };
    int main() {
        pclass<int> p1;
        cout << p1.GetMax(2, 3) << endl;
        pclass<double> p2;
        cout << p2.GetMax(1.66, 5.66) << endl;
        pclass<char> p3;
        cout << p3.GetMax('a', 'p') << endl;
        pclass<string> p4;
        cout << p4.GetMax("string", "ss") << endl;
        return 0;
    }

    也可以通过模板类来初始化类内的成员变量

    #include <iostream>
    #include<string>
    #include <memory>
    using namespace std;
    template<int n,int m>
    class pclass
    {
    public:
        pclass()
        {
            a = n;
            b = m;
        };
        ~pclass()
        {
    
        };
        int GetMax()
        {
            return a > b ? a : b;
        }
    private:
        int a;
        int b;
    };
    int main() {
        pclass<2,3> p1;
        cout << p1.GetMax() << endl;
        return 0;
    }

    三、可变参数模板

    注意的是函数模板和类模板的使用不能混淆,

    函数模板使用是直接传变量值进去,传变量类型会报错

    类模板使用是直接传变量类型,初始化的时候传值进去

    template<class T>
    T GetMax(T a,T b)
    {
        return a>b?a:b;
    }
    
    GetMax(1,2);//正确
    GetMax(int ,int);//错误
    
    template<class T>
    class pclass
    {
        ...
    };
    
    pclass p1<int>;//正确
    pclass p2<2>;//错误
    
    template<int n>
    class pclass
    {
        ...
    };
    
    pclass p1<2>;//正确
    pclass p2<int>;//错误

     模板类的使用不能再main()函数里面,模板类必须是全局变量

  • 相关阅读:
    vue检查用户名是否重复
    后端注册接口完善
    django添加检查用户名和手机号数量接口
    Vue联调,图片及短信验证码
    swift webView 提出这样的要求你能忍吗?
    iOS 如何给Xcode7项目添加“.pch”文件
    swift 定制自己的Button样式
    Swift 为你的webView定制标题
    swift 如何获取webView的内容高度
    如何在MAC上使用SVN,简单几行命令搞定
  • 原文地址:https://www.cnblogs.com/-citywall123/p/12699257.html
Copyright © 2020-2023  润新知