«

1 模板

时间:2023-10-18 23:33     作者:wen     分类: C++


[toc]

模板

模板的概念

模板就是建立通用的模具,大大提高复用性

模板的特点:


模板函数


函数模板的语法

函数模板作用:

建立一个通用的函数,其函数返回值类型和形参类似可以不具体制定,用一个虚拟的类型来代表。

语法:

template<typename T>
函数声明或定义

解释:

template --- 声明创建模板

typename --- 表明其后面的符号是一种数据类型,可以用class代替

T --- 通用的数据类型,名称可以替换,通常为答谢字母

案例:

#include <iostream>
#include <string>
using namespace std;

// 函数模板

// 两个数交换函数
template<typename T>
void myswap(T& a, T& b)
{
    T temp = a;
    a = b;
    b = temp;
}

void testA()
{
    int a = 10;
    int b = 20;
    // 利用函数模板交换
    // 两种方式使用函数模板
    // 1.自动类型推导
    //myswap(a, b);

    // 2.显示指定类型
    myswap<int>(a, b);

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

}

int main()
{
    testA();
    system("pause");
    return 0;
}

总结:


函数模板注意事项

注意事项:

示例:

#include <iostream>
#include <string>
using namespace std;

// 函数模板

// 两个数交换函数
template<class T>
void myswap(T& a, T& b)
{
    T temp = a;
    a = b;
    b = temp;
}

//自动类型推导,必须推导出一致的数据类型T,才可以使用
void testA()
{
    int a = 10;
    int b = 20;
    char c = 'c';

    myswap(a, b); // 正确
    //myswap(a, c); // 错误!推导不出一致的数据类型

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}

template<class T>
void func()
{
    cout << "func 调用" << endl;
}

// 模板必须要确定出T的数据类型,才可以使用
void testB()
{
    //func(); // 错误, 不能确定T的数据类型
    func<int>();
}

int main()
{
    testA();
    testB();
    system("pause");
    return 0;
}


函数模板案例

案例描述:

示例:

#include <iostream>
#include <string>
using namespace std;

// 函数模板

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

template<class T>
void mySort(T arr[], int len)
{
    for (int i = 0; i < len; i++)
    {
        int max = i;
        for (int j = i+1; j < len; j++)
        {
            if (arr[max] < arr[j])
            {
                max = j;
            }
        }
        if (max != i)
        {
            myswap(arr[max], arr[i]);
        }
    }
}

template<typename T>
void myPrint(T arr[], int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}

void testA()
{
    //测试char数组
    char charArr[] = "badcfe";
    mySort(charArr, sizeof(charArr));
    myPrint(charArr, sizeof(charArr));

    // 测试int数组
    int intArr[] = { 7,5,1,3,9,2,4,6,8 };
    int len = sizeof(intArr) / sizeof(int);
    mySort(intArr, len);
    myPrint(intArr, len);
}

int main()
{
    testA();
    system("pause");
    return 0;
}


普通函数与函数模板的区别

普通函数与函数模板的区别:

示例:

#include <iostream>
#include <string>
using namespace std;

// 普通函数
int myAdd01(int a, int b)
{
    return a + b;
 }

// 函数模板
template<class T>
T myAdd02(T a, T b)
{
    return a + b;
}

void testA()
{
    int a = 10;
    int b = 20;
    char c = 'c'; 
    cout << myAdd01(a, b) << endl;
    cout << myAdd01(a, c) << endl; // 发生了隐士类型转换, c=99

    // 自动类型推导
    cout << myAdd02(a, b) << endl;
    //cout << myAdd02(a, c) << endl; // 编译错误, 不能发生隐士类型转换

    // 显示指定类型
    cout << myAdd02<int>(a, c) << endl; // 可以发生隐士类型转换
}

int main()
{
    testA();
    system("pause");
    return 0;
}


普通函数与函数模板的调用规则

调用规则如下:

  1. 如果函数模板和普通函数都可以实现,优先调用普通函数
  2. 可以通过空模板参数列表来强制调用函数模板
  3. 函数模板也可以发送重载
  4. 如果函数模板可以产生更好的匹配,优先调用函数模板

示例:

#include <iostream>
#include <string>
using namespace std;

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

//如果声明函数没有写函数体,也会优先调用,编译会报错
//void myPrint(int a, int b);

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

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

void testA()
{
    int a = 10;
    int b = 20;
    int c = 30;
    myPrint(a, b); // 如果函数模板和普通函数都可以实现,优先调用普通函数

    myPrint<>(a, b); // 通过空模板参数列表来强制调用函数模板

    myPrint(a, b, c); // 函数模板也可以发送重载

    //如果函数模板可以产生更好的匹配,优先调用函数模板
    char c1 = 'a';
    char c2 = 'b';
    myPrint(c1, c2);
}

int main()
{
    testA();
    system("pause");
    return 0;
}

总结:既然提供了函数模板,最好就不要提供普通函数,否则容易出现二义性


模板的局限性

局限性:

例如:

template<class T>
void f(T a, T b)
{
    a = b;
}

在上述代码中提供的赋值操作,如果传入的a和b是一个数组,就无法实现了


再例如:

template<class T>
void f(T a, T b)
{
    if (a > b) {

    }
}

在上述代码中,如果T的数据类型传入的是像Person这样的自定义数据类型,也无法正常运行


因此C++为了解决这种问题,提供模板的重载,可以为这些特点的类型提供具体化的模板


示例:

#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
    Person(string name, int age):m_Name(name),m_Age(age) {

    }

public:
    string m_Name;
    int m_Age;
};

template <class T>
bool myCompare(T& a, T& b)
{
    if (a == b)
    {
        return true;
    }
    else {
        return false;
    }
}

// 利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person& p1, Person& p2)
{
    if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age)
    {
        return true;
    }
    else {
        return false;
    }
}

void testA()
{
    Person p1("Tom",10);
    Person p2 = {"Tom",20};
    cout << myCompare(p1, p2) << endl;
}

int main()
{
    testA();
    system("pause");
    return 0;
}

总结:


类模板

类模板语法

类模板作用:


语法:

template<typename T>
类

解释:

template --- 声明创建模板

typename --- 表示其后面的符号是一种数据类型,可以用class代替

T --- 通用的数据类型,名称可以替换,通常为大写字母


示例:

#include <iostream>
#include <string>
using namespace std;

// 类模板
template <class NameType,class AgeType>
class Person
{
public:
    Person(NameType name, AgeType age):m_Name(name),m_Age(age) {

    }

    void showPerson()
    {
        cout << "姓名:" << this->m_Name << "\t年龄:" << m_Age << endl;
    }

public:
    NameType m_Name;
    AgeType m_Age;
};

void testA()
{
    Person<string,int> p1("Tom",10);
    p1.showPerson();
    Person<string, int> p2 = {"孙悟空", 99};

    p2.showPerson();
}

int main()
{
    testA();
    system("pause");
    return 0;
}


类模板与函数模板的区别

类模板与函数模板的区别只要有两点:

  1. 类模板没有自动类型推导的使用方式
  2. 类模板在模板参数列表中可以有默认参数

示例:

#include <iostream>
#include <string>
using namespace std;

// 类模板
//2.类模板在模板参数列表中可以有默认参数
template <class NameType,class AgeType = int>
class Person
{
public:
    Person(NameType name, AgeType age):m_Name(name),m_Age(age) {

    }

    void showPerson()
    {
        cout << "姓名:" << this->m_Name << "\t年龄:" << m_Age << endl;
    }

public:
    NameType m_Name;
    AgeType m_Age;
};

/*
1.类模板没有自动类型推导的使用方式
*/
void testA()
{
    //Person p("孙悟空",1000) // 编译错误, 无法自动类型推导
    Person<string> p1("猪八戒",999);
    p1.showPerson();
}

int main()
{
    testA();
    system("pause");
    return 0;
}


类模板中成员函数创建时机

类模板中成员函数和普通类中成员函数创建时机是有区别的:

示例:

#include <iostream>
#include <string>
using namespace std;

// 类模板中的成员函数的创建时机

class Person1
{
public:
    void showPerson1()
    {
        cout << "show person1" << endl;
    }
};

class Person2
{
public:
    void showPerson2()
    {
        cout << "show person1" << endl;
    }
};

template <class T>
class MyClass
{

public:
    T obj;

    void func1()
    {
        obj.showPerson1();
    }

    void func2()
    {
        obj.showPerson2();
    }
};

//类模板中的成员函数在调用是才创建
void testA()
{
    MyClass<Person1> m;
    m.func1();
    m.func2(); // 编译出错
}

int main()
{
    testA();
    system("pause");
    return 0;
}



类模板对象做函数参数

学习目标:


一共三种传入方式:

  1. 指定传入的类型 --- 直接显示对象的数据类型
  2. 参数模板化 --- 将对象中的参数变为模板进行传递
  3. 整个类模板化 --- 将这个对象类型模板化进行传递

示例:

#include <iostream>
#include <string>
using namespace std;

//类模板对象做函数参数

/*
1.指定传入的类型 --- 直接显示对象的数据类型
2.参数模板化 --- 将对象中的参数变为模板进行传递
3.整个类模板化 --- 将这个对象类型模板化进行传递
*/

template<class T1,class T2>
class Person
{
public:
    T1 m_Name;
    T2 m_Age;

public:
    Person(T1 name, T2 age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }

    void showPerson()
    {
        cout << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
    }
};

/// <summary>
/// 1.指定传入的类型
/// </summary>
/// <param name="p"></param>
void printPerson1(Person<string, int>& p)
{
    p.showPerson();
}

void testA()
{
    Person<string, int> p("孙悟空", 1000);
    printPerson1(p);
}

/// <summary>
/// 2.参数模板化
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="p"></param>
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;
}

void testB()
{
    Person<string, int> p("猪八戒", 900);
    printPerson2(p);
}

/// <summary>
/// 3.整个类模板化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p"></param>
template<class T>
void printPerson3(T& p)
{
    p.showPerson();
    cout << "T的类型为:" << typeid(T).name() << endl;
}

void testC()
{
    Person<string, int> p("唐僧", 30);
    printPerson3(p);
}

int main()
{
    testA();
    testB();
    testC();
    system("pause");
    return 0;
}

总结:


类模板与继承

当类模板碰到继承时,需要注意以下几点:

示例:

#include <iostream>
#include <string>
using namespace std;

// 类模板与继承
template <class T>
class Base
{
    T m;
};

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

};

void testA()
{
    Son s1;
}

//如果想灵活指定出父类中T的类型,子类也需要变为类模板
template<class T1,class T2>
class Son2 :public Base<T2>
{
public:
    T1 obj;

    Son2()
    {
        cout << "T1的类型为:" << typeid(T1).name() << endl;
        cout << "T2的类型为:" << typeid(T2).name() << endl;
    }
};

void testB()
{
    Son2<int, char>s2;

}

int main()
{
    testA();
    testB();
    system("pause");
    return 0;
}


类模板成员函数类外实现

学习目标:能够掌握类模板中的成员函数类外实现

示例:

#include <iostream>
#include <string>
using namespace std;

//类模板中的成员函数类外实现
template<class T1,class T2>
class Person
{
public:
    T1 m_Name;
    T2 m_Age;
public:

    Person(T1 name, T2 age);
    /*{
        this->m_Name = name;
        this->m_Age = age;
    }*/

    void showPerson();
    /*{
        cout << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
    }*/
};

// 构造函数类外实现
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 << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
}

void testA()
{
    Person<string, int> p("Tom", 20);
    p.showPerson();
}

int main()
{
    testA();
    system("pause");
    return 0;
}

总结:类模板中成员函数类外实现,需要加上模板参数列表


类模板分文件编写

学习目标:


问题:

解决:


示例:

person.hpp中代码

#include <iostream>
#include <string>
using namespace std;

// 类模板分文件编写问题和解决
#include "Person.hpp"

void testA()
{
    Person<string, int> p("Tom", 20);
    p.showPerson();
}

int main()
{
    testA();
    system("pause");
    return 0;
}

main.cpp中代码

#include <iostream>
#include <string>
using namespace std;

// 类模板分文件编写问题和解决
#include "Person.hpp"

void testA()
{
    Person<string, int> p("Tom", 20);
    p.showPerson();
}

int main()
{
    testA();
    system("pause");
    return 0;
}


类模板与友元

学习目标:

全局函数类内实现 - 直接在类内声明友元即可

全局函数类外实现 - 需要提前让编译器知道全局函数存在


示例:

#include <iostream>
#include <string>
using namespace std;

// 通过全局函数 打印Person信息
// 提前让编译器知道全局函数存在
template<class T1, class T2>
class Person;
template<class T1, class T2>
void printPerson2(Person<T1, T2>& p);

template<class T1,class T2>
class Person
{
    //全局函数 类内实现
    friend void printPerson(Person<T1, T2>& p)
    {
        cout << "姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl;
    }

    //全局函数 类外实现
    //加空模板参数列表
    //如果全局函数是类外实现 需要提前让编译器知道全局函数存在
    friend void printPerson2<>(Person<T1, T2>& p);

public:
    Person(T1 name, T2 age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }

private:
    T1 m_Name;
    T2 m_Age;
};

template<class T1, class T2>
void printPerson2(Person<T1, T2>& p)
{
    cout << "内外实现---姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl;
}

void testA()
{
    Person<string, int> p("Tom", 20);
    printPerson(p);
    printPerson2(p);
}

int main()
{
    testA();
    system("pause");
    return 0;
}


类模板案例

案例描述:实现一个通用的数组类,要求如下:

示例:

myArray.hpp中代码

#pragma once
#include <iostream>
using namespace std;
#include <string>

template<class T>
class MyArray
{
public:
    // 有参构造
    MyArray(int capacity)
    {
        //cout << "myarray的有参构造调用" << endl;
        this->m_Capacity = capacity;
        this->m_Size = 0;
        this->pAddress = new T[this->m_Capacity];
    }
    //拷贝构造
    MyArray(const MyArray& arr)
    {
        //cout << "myarray的拷贝构造调用" << endl;
        this->m_Capacity = arr.m_Capacity;
        this->m_Size = arr.m_Size;
        //浅拷贝
        //this->pAddress = arr.pAddress;
        //深拷贝
        this->pAddress = new T[arr.m_Capacity];

        //将arr中的数据都拷贝过来
        for (int i = 0; i < this->m_Size; i++)
        {
            this->pAddress[i] = arr.pAddress[i];
        }

    }

    //operator= 防止浅拷贝问题
    MyArray& operator=(const MyArray& arr)
    {
        //cout << "myarray的=构造调用" << 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 = arr.pAddress;
        //深拷贝
        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;
    }

    // 尾插法
    void pushBack(const T& val)
    {
        //判断容量是否等于大小
        if (this->m_Capacity == this->m_Size)
        {
            return;
        }

        this->pAddress[this->m_Size] = val;
        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;
    }

    // 析构函数
    ~MyArray()
    {
        //cout << "myarray的析构构造调用" << endl;
        if (this->pAddress != NULL)
        {
            delete[] this->pAddress;
            this->pAddress = NULL;
        }
    }

private:
    T* pAddress; //指针指向堆区开辟的真实数组

    int m_Capacity; //数组容量

    int m_Size; //数组大小
};

main.cpp中代码

#include <iostream>
#include <string>
using namespace std;

#include "MyArray.hpp"

template<class T>
void printArray(MyArray<T>& arr)
{
    for (int i = 0; i < arr.getSize(); i++)
    {
        cout << arr[i] << endl;
    }
}

void testA()
{
    MyArray<int> arr1(5);
    for (int i = 0; i < 5; i++)
    {
        arr1.pushBack(i);
    }
    cout << "arr1打印输出:" << endl;
    printArray(arr1);
    cout << "arr1的容量为:" << arr1.getCapacity() << endl;
    cout << "arr1的大小为:" << arr1.getSize() << endl;

    MyArray<int>arr2(arr1);
    cout << "arr2打印输出:" << endl;
    printArray(arr2);

    //尾删
    arr2.popBack();
    cout << "arr2的容量为:" << arr2.getCapacity() << endl;
    cout << "arr2的大小为:" << arr2.getSize() << endl;
    cout << "arr2尾删后打印输出:" << endl;
    printArray(arr2);
}

//测试自定义数据类型
class Person
{
public:

    Person(string name,int age)
    {
        this->m_Age = age;
        this->m_Name = name;
    }

public:
    string m_Name;
    int m_Age;

    Person() = default;

};

void printPersonArray(MyArray<Person>& arr)
{
    for (int i = 0; i < arr.getSize(); i++)
    {
        cout << "姓名:" << arr[i].m_Name << "\t年龄:" << arr[i].m_Age << endl;
    }
}

void testB()
{
    MyArray<Person> arr(10);

    Person p1("孙悟空", 999);
    Person p2("韩信", 30);
    Person p3("妲己", 20);
    Person p4("赵云", 25);
    Person p5("安其拉", 20);

    arr.pushBack(p1);
    arr.pushBack(p2);
    arr.pushBack(p3);
    arr.pushBack(p4);
    arr.pushBack(p5);

    printPersonArray(arr);

    cout << "arr的容量为:" << arr.getCapacity() << endl;
    cout << "arr的大小为:" << arr.getSize() << endl;
}

int main()
{
    //testA();
    testB();
    system("pause");
    return 0;
}

标签: C/C++ c++提高编程