C++-模板

本文介绍了C++中的模板和typename关键字,展示了如何使用它们实现泛型编程。通过冒泡排序和自定义Array类的示例,阐述了模板的工作原理和使用方式,包括类型推断和模板实例化。强调了typename在处理依赖于上下文的类型名称时的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

戳进来的可以直接看文末的英文链接…
C++添加了两个新关键子来支持模板:
template and typename
typename keyword can always be replaced by keyword class

模板是在编译时进行"拓展"的,就像宏一样.不同点在于,编译器在模板拓展前会做类型检查.
模板机制在于源码只包含一个函数/类的代码,但是经过编译的代码可能包含同一函数/类的多份拷贝.
解释如下图:
在这里插入图片描述
代码实例:冒泡排序


// CPP code for bubble sort
// using template function
#include <iostream>
using namespace std;
  
// A template function to implement bubble sort.
// We can use this for any data type that supports
// comparison operator < and swap works for it.
template <class T>
void bubbleSort(T a[], int n) {
    for (int i = 0; i < n - 1; i++)
        for (int j = n - 1; i < j; j--)
            if (a[j] < a[j - 1])
              swap(a[j], a[j - 1]);
}
  
// Driver Code
int main() {
    int a[5] = {10, 50, 30, 40, 20};
    int n = sizeof(a) / sizeof(a[0]);
  
    // calls template function
    bubbleSort<int>(a, n);
  
    cout << " Sorted array : ";
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
  
  return 0;
}

观察函数的声明,发现声明前有一个template用来表明这是一个模板,同时在参数中可以观察到T a[].
观察函数的调用,发现调用处为

 bubbleSort<int>(a, n);

注意到在函数名后有个< int >

代码示例:自定义Array

#include <iostream>
using namespace std;

template <typename T>
class Array {
private:
    T *ptr;
    int size;
public:
    Array(T arr[], int s);
    void print();
};

template <typename T>
Array<T>::Array(T arr[], int s) {
    ptr = new T[s];
    size = s;
    for(int i = 0; i < size; i++)
        ptr[i] = arr[i];
}

template <typename T>
void Array<T>::print() {
    for (int i = 0; i < size; i++)
        cout<<" "<<*(ptr + i);
    cout<<endl;
}

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    Array<int> a(arr, 5);
    a.print();
    return 0;
}

更多相关内容可以看这篇博客:
传送门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值