C++基础学习--模板机制

C++模板机制

C++的模板机制分为函数模板和类模板,类似于类与实例,类是一个抽象的概念,实例是具体的概念,对于模板来说类模板是抽象概念,类是具体概念;函数模板类似

函数模板

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <queue>
#include "main.h"
using namespace std;

template <typename type>

void test(type &a, type &b)
{
    type c;
    c = a;
    a = b;
    b = c;
}
int main()
{
    // 利用函数模板实现获取最大值
    int a = 12;
    int b = 34;
    test(a, b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}

类模板

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <queue>
#include "main.h"
using namespace std;

template<class numType>
class Compare {
public:
    Compare() = default;
    Compare(numType arg):age(arg){};
    ~Compare() = default;
    void display()
    {
        printf("this is %d\n", age);
    }
private:
    numType age;
    numType high;
};

int main()
{
    // 利用函数模板实现一个实体类
    Compare<int>cmp1(10);
    cmp1.display();
    Compare<char>cmp2('a');
    cmp2.display();
    return 0;
}
posted @ 2021-03-16 01:03  WangCoder  阅读(106)  评论(0编辑  收藏  举报