C++之函数模板
C++中有很多函數(shù)僅僅是參數(shù)類型不同,但是實(shí)現(xiàn)過程相似,可以寫一個(gè)通用的函數(shù),使用非實(shí)例化的參數(shù)類型,該參數(shù)在函數(shù)被調(diào)用時(shí)進(jìn)行實(shí)例化,這種函數(shù)稱之為模板函數(shù)
普通函數(shù):參數(shù)值未定,但參數(shù)類型已知
模板函數(shù):參數(shù)值和參數(shù)類型均為未知
template <class T>//T表示未確定的模板參數(shù)類型
void function(T ...)
這里給出實(shí)例
#include "stdafx.h" #include<stdlib.h> #include<iostream>using namespace std;template <class T>//表示T是一個(gè)未知類型 void printArray(T *arr, int size) {int i;for ( i = 0; i < size; i++){ cout << arr[i];if(i<(size -1))cout << " , ";}cout << endl; }int main() {const int max = 5;int iArray[max] = { 10,20,30,40,50 };float fArray[max] = { 1.2,3.5,4.6,8.9,12.3 };const char* cArray[max] = { "one","two","three","four","five" };//調(diào)用模板函數(shù)printArray(iArray, max);printArray(fArray, max);printArray(cArray, max);system("pause");return 0; }
總結(jié)
- 上一篇: C++之异常处理
- 下一篇: s3c2440移植MQTT