C++模板的一些基础知识

一.函数模板

可看出就是将函数返回类型和形参类型去掉。

1.代码1

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

template<typename T>
void swap_(T& a, T& b ){
    T temp = a;
    a = b;
    b = temp;
}
int main()
{

    //1.自动类型推导 必须要一致的数据类型才可用
    int a1 = 10, b1 = 20;
    cout<<a1<<" "<<b1<<endl;
    swap_(a1, b1);
    cout<<a1<<" "<<b1<<endl;

    float a2 = 10.01, b2 = 20.55;
    cout<<a2<<" "<<b2<<endl;
    swap_(a2, b2);
    cout<<a2<<" "<<b2<<endl;

    //2.显示指定类型
    swap_<int>(a1, b1);
    cout<<a1<<" "<<b1<<endl;
    swap_<float>(a2, b2);
    cout<<a2<<" "<<b2<<endl;
    return 0;
}

有两种使用方式,一个是自动类型推导(必须要一致的数据类型才可用),一个是显示指定类型。

2.代码2

将类型作为参数,用template修饰函数模板,解决不同类型函数但实现逻辑一样的问题

#include <iostream>
using namespace std;


template <typename T>//函数模板
void display(T a)
{
    cout<<"a:"<<a<<endl;
    cout<<"======="<<endl;
}

template <typename T,typename S>//函数模板
void display(T t, S s)
{   
    cout<<"t:"<<t<<endl;
    cout<<"s:"<<s<<endl;
    cout<<"======="<<endl;
}

template <typename T,int KSize>//函数模板
void display(T a)
{
    for (int i=0;i<KSize;i++)
    {
        cout<<"a:"<<a<<endl;
    }

}

int main()
{   
    display<int>(10);//模板函数
    display<double>(10.89);//模板函数

    display<int,float>(11,12.11);//模板函数


    display<int, 5>(11);
    return 0;
}

3.代码3

选择排序,降序排序

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

template<typename T>
void swap_(T& a, T& b){
    T temp = a;
    a = b;
    b = temp;
}

//从大到小排序
template<typename T>
void sort_(T& arr){
    int n = sizeof(arr) / sizeof(arr[0]);
    for(int i = 0; i < n; i++){
        int index = i;
        for(int j = i + 1; j < n; j++){
            if(arr[index] < arr[j]){
                index = j;
            }
        }
        if(index != i){
            swap_(arr[index], arr[i]);
        }
    }
}
template <typename T>
void printArr(T& arr){
    int n = sizeof(arr) / sizeof(arr[0]);
    for(int i = 0; i < n; i++ ){
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}
int main()
{
//    test06();
    char charArr[] =  "bdfdsskn";
    sort_(charArr);
    printArr(charArr);

    int intArr[] =  {6, 7, 4, 6, 8, 2, 3, 7};
    sort_(intArr);
    printArr(intArr);
    return 0;
}

4.普通函数和模板函数的调用规则

4.1如果函数模板和普通函数都可以调用,优先调用普通函数

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//
void myPrint(int a, int b){
    cout<<"调用的普通函数"<<endl;
}

template <typename T>
void myPrint(T a, T b){
    cout<<"调用的函数模板"<<endl;
}
void test06(){
   int a = 10, b = 20;
   //如果函数模板和普通函数都可以调用,优先调用普通函数
   myPrint(a, b);
}
int main()
{
    test06();
    return 0;
}

4.2通过空模板参数列表,强制调用函数模板

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//
void myPrint(int a, int b){
    cout<<"调用的普通函数"<<endl;
}

template <typename T>
void myPrint(T a, T b){
    cout<<"调用的函数模板"<<endl;
}
void test06(){
   int a = 10, b = 20;
  // 通过空模板参数列表,强制调用函数模板
   myPrint<>(a, b);
}
int main()
{
    test06();
    return 0;
}

4.3重载函数模板

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//
void myPrint(int a, int b){
    cout<<"调用的普通函数"<<endl;
}

template <typename T>
void myPrint(T a, T b){
    cout<<"调用的函数模板"<<endl;
}

template <typename T>
void myPrint(T a, T b, T c){
    cout<<"调用的重载函数模板"<<endl;
}
void test06(){
   int a = 10, b = 20;
  // 通过 空模板参数列表,强制调用模板函数
   myPrint<>(a, b);
   myPrint<>(a, b, 100);
}
int main()
{
    test06();
    return 0;
}

4.4 如果函数模板能够产生更好的匹配,优先使用函数模板

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//
void myPrint(int a, int b){
    cout<<"调用的普通函数"<<endl;
    cout<<"a:"<<a<<endl;
    cout<<"b:"<<b<<endl;
}

template <typename T>
void myPrint(T a, T b){
    cout<<"调用的函数模板"<<endl;
    cout<<"a:"<<a<<endl;
    cout<<"b:"<<b<<endl;
}

template <typename T>
void myPrint(T a, T b, T c){
    cout<<"调用的重载函数模板"<<endl;
    cout<<"a:"<<a<<endl;
    cout<<"b:"<<b<<endl;
    cout<<"c:"<<c<<endl;
}
void test06(){
   int a = 10, b = 20;
   char c1 = 'a';
   char c2 = 'b';
  // 优先将T推导为char 类型
   myPrint(c1, c2);
}
int main()
{
    test06();
    return 0;
}

可看出优先将T转换成char,而不是将char字符一个一个转换成int类型。 

二.类模板

类模板语法和函数模板语法很接近,都是先声明模板出来。

与函数模板差异

1.代码1:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

template <class NameType, class AgeType>
class Person{
public:
    Person(NameType name, AgeType age){
        this->m_Name = name;
        this->m_Age = age;
    }
    void showPerson(){
        cout<<"name:"<<this->m_Name<<" age:"<<this->m_Age<<endl;
    }
    NameType m_Name;
    AgeType m_Age;
};

void test06(){
   Person<string, int> p1("lining", 13);
   p1.showPerson();
}
int main()
{
    test06();
    return 0;
}

 

MyArray.h

#ifndef MYARRAY_H
#define MYARRAY_H
#include <iostream>
using namespace std;

template <typename T, int KSize, int KVal>//T就是要定义的类型

class MyArray
{
    public:
        MyArray();
        ~MyArray()
        {
            delete []m_pArr;
            m_pArr=NULL;
        };
        void display();
    private:
        T *m_pArr;
};

template <typename T,int KSize, int KVal>//函数定义时 一定要写
MyArray<T, KSize, KVal>::MyArray()
{
    m_pArr = new T[KSize];
    for (int i=0;i<KSize;i++)
    {
        m_pArr[i] = KVal;
    }
}

template <typename T,int KSize, int KVal>//函数定义时 一定要写
void MyArray<T, KSize, KVal>::display()
{
    for (int i=0;i<KSize;i++)
    {
        cout<<"m_pArr[i]:"<<m_pArr[i]<<endl;
    }
}

#endif

demo.cpp

#include <iostream>
#include <string>
#include "MyArray.h"
using namespace std;

int main()
{   
    
    MyArray<int, 5, 6> arr;//每个元素都是6共5个元素的数组
    arr.display();
    return 0;
}

2.与函数模板差异

1.类模板没有自动推导方式

2.类模板中的参数列表可以有默认类型

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;
//类模板中的参数列表可以有默认类型
template <class NameType, class AgeType = int>
class Person{
public:
    Person(NameType name, AgeType age){
        this->m_Name = name;
        this->m_Age = age;
    }
    void showPerson(){
        cout<<"name:"<<this->m_Name<<" age:"<<this->m_Age<<endl;
    }
    NameType m_Name;
    AgeType m_Age;
};

void test06(){
//   Person p1("lining", 13); //错误的
//   Person<string, int> p2("lining", 13);
    Person<string> p2("lining", 13); //有默认类型所以这里可以省去int
    p2.showPerson();
}
int main()
{
    test06();
    return 0;
}

3.类模板中成员函数和普通类成员函数创建方式

因为不知道是啥类型, 类模板中的成员函数在调用时才创建

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;
//类模板中的成员函数在调用时才创建 (因为不知道是啥类型)
//普通类中的成员函数一开始就创建
class Person1{
public:
    void showPerson1(){
        cout<<"showPerson1()"<<endl;
    }
};

class Person2{
public:
    void showPerson2(){
        cout<<"showPerson2()"<<endl;
    }
};
template<class T>
class Myclass{
public:
    T obj;
    //类模板中的成员函数
    void func1(){
        obj.showPerson1();
    }
    void func2(){
        obj.showPerson2();
    }
};
void test06(){
    Myclass<Person1> m;
    m.func1();
    m.func1();
}

int main()
{
    test06();
    return 0;
}

4.类模板对象做函数参数

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;
//类模板对象做函数参数
template<class T1, class T2>
class Person{
public:
    Person(T1 name, T2 age){
        this->m_Name = name;
        this->m_Age = age;
    }
    void showPerson(){
        cout<< "姓名: " << this->m_Name <<" 年龄: "<< this->m_Age <<endl;
    }
    T1 m_Name;
    T2 m_Age;
};

//1.指定传入类型 (最常用)
void printPerson1(Person<string, int>&p){
    p.showPerson();
}
//2.参数模板化
template<class T1, class T2>
void printPerson2(Person<T1, T2>&p){
    p.showPerson();
    cout<<"T1类型: "<<typeid(T1).name()<<endl;
    cout<<"T2类型: "<<typeid(T2).name()<<endl;
}
//3.整个类模板化
template<class T>
void printPerson3(T &p){
    p.showPerson();
    cout<<"T类型: "<<typeid(T).name()<<endl;
}
void test06(){
    Person<string, int>p("limin", 100);
    printPerson1(p);
    printPerson2(p);
    printPerson3(p);
}

int main()
{
    test06();
    return 0;
}

5.类模板与继承

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

template<class T>
class Base{
public:
    T m;
};
//class Son1:public Base{ //错误的,必须要知道父类中的T类型,才能继承给子类
class Son1:public Base<int>{

};
template<class T1, class T2>
class Son2:public Base<T2>{ //如果想灵活指定父类中的T类型,子类也需要变类模板
public:
    Son2(){
        cout<<" T1类型: "<<typeid(T1).name()<<endl;
        cout<<" T2类型: "<<typeid(T2).name()<<endl;
    }
    T1 obj;
};

void test06(){
    Son1 s1;
    Son2<int, char> s2;
}

int main()
{
    test06();
    return 0;
}

6.类模板成员函数类外实现

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//类模板成员函数类外实现
template<class T1, class T2>
class Person{
public:
    Person(T1 name, T2 age);
    //类内实现构造函数
//    Person(T1 name, T2 age){
//        this->m_Name = name;
//        this->m_Age = age;
//    }
//    void showPerson(){
//        cout<<" 姓名: "<<this->m_Name<< " 年龄: " <<this->m_Age<<endl;
//    }
    void showPerson();
    T1 m_Name;
    T2 m_Age;
};
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age){
    this->m_Name = name;
    this->m_Age = age;
}
//成员函数类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson(){
    cout<<" 姓名: "<<this->m_Name<< " 年龄: " <<this->m_Age<<endl;
}
void test06(){
    Person<string, int>p("limin", 100);
    p.showPerson();
}

int main()
{
    test06();
    return 0;
}

7.类模板类分文件编写

7.1.第一种方式:因为类模板成员函数一开始是不会创建的,所以包含.h头文件不会创建类模板成员函数,导致链接阶段无法找到。而改为#include .cpp就可以看见.h成员函数和实现方式.

demo.cpp

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
//#include "Person.h" //错误不能调用
#include "Person.cpp" //改为.cpp文件就行
//#include "Person.hpp" //改为.hpp文件就行 里面包含函数声明与实现
using namespace std;

void test06(){
    Person<string, int>p("limin", 100);
    p.showPerson();
}

int main()
{
    test06();
    return 0;
}

Person.h

#pragma once //防止头文件重复包含
#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//类模板成员函数类外实现
template<class T1, class T2>
class Person{
public:
    Person(T1 name, T2 age);
    void showPerson();
    T1 m_Name;
    T2 m_Age;
};

Person.cpp

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
#include "Person.h"
using namespace std;
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age){
    this->m_Name = name;
    this->m_Age = age;
}
//成员函数类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson(){
    cout<<" 姓名: "<<this->m_Name<< " 年龄: " <<this->m_Age<<endl;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)
project(Infantry)
add_definitions(-std=c++11)
set(CMAKE_BUILD_TYPE Debug)
set(SRC_LIST demo.cpp Person.cpp Person.h)
#set(SRC_LIST demo.cpp Person.hpp)
add_executable(demo ${SRC_LIST})

7.2函数声明和实现都在.hpp。

Person.hpp 

#pragma once //防止头文件重复包含
#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//类模板成员函数类外实现
template<class T1, class T2>
class Person{
public:
    Person(T1 name, T2 age);
    void showPerson();
    T1 m_Name;
    T2 m_Age;
};
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age){
    this->m_Name = name;
    this->m_Age = age;
}
//成员函数类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson(){
    cout<<" 姓名: "<<this->m_Name<< " 年龄: " <<this->m_Age<<endl;
}

demo.cpp 

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
//#include "Person.h" //错误不能调用
//#include "Person.cpp" //改为.cpp文件就行
#include "Person.hpp" //改为.hpp文件就行 里面包含函数声明与实现
using namespace std;

void test06(){
    Person<string, int>p("limin", 100);
    p.showPerson();
}

int main()
{
    test06();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)
project(Infantry)
add_definitions(-std=c++11)
set(CMAKE_BUILD_TYPE Debug)
#set(SRC_LIST demo.cpp Person.cpp Person.h)
set(SRC_LIST demo.cpp Person.hpp)
add_executable(demo ${SRC_LIST})

8.类模板配合友元函数的类内和类外实现

8.1.全局函数类内实现

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

template<class T1, class T2>
class Person{
    //全局函数 类内实现
    friend void printPerson(Person<T1, T2> p){
        cout<<" 姓名: "<<p.m_Name<< " 年龄: " <<p.m_Age<<endl;
    }
public:
    Person(T1 name, T2 age){
        this->m_Name = name;
        this->m_Age = age;
    }
//    void showPerson(){
//        cout<<" 姓名: "<<this->m_Name<< " 年龄: " <<this->m_Age<<endl;
//    }
private:
    T1 m_Name;
    T2 m_Age;
};
void test06(){
    //全局函数类内实现的测试
    Person<string, int>p("limin", 100);
    printPerson(p);
}

int main()
{
    test06();
    return 0;
}

8.2 全局函数类外实现

如果全局函数是类外实现的话 需要编译器提前知道这个函数的存在

 

9.案例

MyClass.hpp

#pragma once //防止头文件重复包含
#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
using namespace std;

//类模板成员函数类外实现
template<class T>
class MyArray{
public:
    //有参构造
    MyArray(int capacity){
        cout<<"调用构造函数"<<endl;
        this->m_capacity = capacity;
        this->m_size = 0;
        this->pAddress = new T[this->m_capacity]; //开辟堆区空间
    }
    //拷贝构造函数
    MyArray(const MyArray<T>& arr){
        cout<<"调用拷贝构造函数"<<endl;
        this->m_capacity = arr.m_capacity;
        this->m_size = arr.m_size;

        this->pAddress = new T[arr.m_capacity];//深拷贝
        //将arr中的数据拷贝过来
        for(int i=0; i<this->m_size; i++){
            this->pAddress[i] = arr.pAddress[i];
        }
    }
    //尾插法
    void PushBack(const T& value){
        //先判断是否等于大小
        if(this->m_capacity == this->m_size){
            return;
        }
        this->pAddress[this->m_size] = value; //尾插法
        this->m_size++; //更新数组大小
    }
    //尾删法
    void PopBack(){
        //让用户访问不了最后一个元素
        if(this->m_size == 0){
            return;
        }
        this->m_size--; //更新数组大小
    }
    //通过下标方式访问数组中元素
    T& operator[](int index){
        return this->pAddress[index];
    }
    //返回数组容量
    int getCapacity(){
        return this->m_capacity;
    }
    //返回数组大小
    int getSize(){
        return this->m_size;
    }
    //operator= 也是防止浅拷贝
    MyArray& operator=(const MyArray<T>& arr){
        cout<<"调用operator= 函数"<<endl;
        //先判断原来堆区是否与数据,如果有先释放
        if(this->pAddress != NULL){
            delete []this->pAddress;
            this->pAddress = NULL;
            this->m_capacity = 0;
            this->m_size = 0;
        }
        //深拷贝
        this->m_capacity = arr.m_capacity;
        this->m_size = arr.m_size;
        this->pAddress = new T[arr.m_capacity];//深拷贝
        //将arr中的数据拷贝过来
        for(int i=0; i<this->m_size; i++){
            this->pAddress[i] = arr.pAddress[i];
        }
        return *this;
    }
    virtual ~MyArray(){
        cout<<"调用析构函数"<<endl;
        if(this->pAddress != NULL){
            delete []this->pAddress;
            this->pAddress = NULL;
        }
    }
private:
    int m_capacity;
    int m_size;
    T* pAddress; //指针指向堆区开辟的真实数组
};

demo.cpp

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include <algorithm>
#include <map>
#include <fstream>
#include "MyClass.hpp"
using namespace std;

void test06(){
    MyArray<int> arr1(20);
    MyArray<int> arr2(arr1);
    MyArray<int> arr3(10);
    arr3 = arr1;
    for(int i=0; i<5; i++){
        arr1.PushBack(i + 10);
    }
    cout<<" ==before arr1.getCapacity(): "<<arr1.getCapacity()<<endl;
    cout<<" ==before arr1.getSize(): "<<arr1.getSize()<<endl;
    for(int i=0; i<arr1.getSize(); i++){
        cout<<"before arr1[i]: " <<arr1[i]<<endl;
    }
    arr1.PopBack();
    arr1.PopBack();
    cout<<" ==after arr1.getCapacity(): "<<arr1.getCapacity()<<endl;
    cout<<" ==after arr1.getSize(): "<<arr1.getSize()<<endl;
    for(int i=0; i<arr1.getSize(); i++){
        cout<<"after arr1[i]: " <<arr1[i]<<endl;
    }
}
class Person{
public:
    Person(){};
    Person(string name, int age){
        this->m_Name = name;
        this->m_Age = age;
    };
    string m_Name;
    int m_Age;
};

void printPersonArray(MyArray<Person>& arr){
    for(int i=0; i<arr.getSize(); i++){
        cout<<" 姓名: "<<arr[i].m_Name<< " 年龄: "<<arr[i].m_Age<<endl;
    }
}
//测试自定义类型
void test07(){
    MyArray<Person> arr(10);
    Person p1("Damin",100);
    Person p2("Tony",70);
    Person p3("Tom",50);
    Person p4("Jarry",10);
    Person p5("Dalin",20);
    arr.PushBack(p1);
    arr.PushBack(p2);
    arr.PushBack(p3);
    arr.PushBack(p4);
    arr.PushBack(p5);
    printPersonArray(arr);
    cout<<" ==arr1.getCapacity(): "<<arr.getCapacity()<<endl;
    cout<<" ==arr1.getSize(): "<<arr.getSize()<<endl;
}

int main()
{
//    test06();
    test07();
    return 0;
}

测试int类型:

测试自定义类型Person:

参考:

https://www.bilibili.com/video/BV1et411b73Z?p=175&spm_id_from=pageDriver

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值