• C++泛型编程、模板


    模板的定义

    模型形参表不能为空

    //  比较器
    template <tempname T>
    int compare(const T &v1, const T &v2)
    {
        if (v1 < v2) return -1;
        if (v2 < v2) return 1;
        return 0;
    }
    

    inline函数模板定义

    template <tempname T> inline int compare(const T &v1, const T &v2);
    

    类模板定义

    #include <iostream>
    #include <string>
    using namespace std;
    template <class T1,class T2>
    class Pair
    {
    public:
        T1 key;  //关键字
        T2 value;  //值
        Pair(T1 k,T2 v):key(k),value(v) { };
        bool operator < (const Pair<T1,T2> & p) const;
    };
    
    // Pair的成员函数 operator <
    template<class T1,class T2>
    bool Pair<T1,T2>::operator < (const Pair<T1,T2> & p) const
    {
        return key < p.key;
    }
    
    int main()
    {
        Pair<string,int> student("Tom",19); //实例化出一个类 Pair<string,int>
        cout << student.key << " " << student.value;
        return 0;
    }
    

    非类型模板形参

    //  T是类型模板形参, N是非类型模板形参
    template <tempname T, size_t N> void init_array(T (&parm)[N])
    {
        for (size_t i = 0; i != N; ++i)
        {
            parm[i] = 0;
        }
    }
    
    int x[42];
    double y[10];
    init_array(x);    //  init_array[int y[42]);
    init_array(y);    //  init_array[double y[10]);
    
  • 相关阅读:
    7-4
    7-3
    第五章例5-2
    第五章例5-1
    第四章例4-12
    第四章例4-11
    第四章例4-10
    第四章例4-9
    第四章例4-8
    第四章例4-7
  • 原文地址:https://www.cnblogs.com/xiongyungang/p/11867660.html
Copyright © 2020-2023  润新知