戳进来的可以直接看文末的英文链接…
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;
}
更多相关内容可以看这篇博客:
传送门