天天看點

【C++】函數模闆(template)

目錄

函數模闆的定義

函數模闆的使用

函數模闆就是可以自動更改資料類型。

函數模闆的定義

定義一個模闆,能夠适應多種類型。

文法規則:

template <typename T>
T findmax (T arr[], int len)
{
    T val = arr[0];
    ...
}
           

(1)算法相同;

(2)元素類型不同,用T代替。

函數模闆的使用

單個模闆參數

#include "stdafx.h"
#include <stdio.h>

template <typename T> //類型可自己定義
T find_max(T arr[], int len)
{
	T val = arr[0];
	for (int i=1; i<len; i++)
	{
		if (arr[i] > val) val = arr[i];
	}
	return val;
}

int main()
{
	int arr[4] = { 1,2,3,4 };
	int result = find_max <int>(arr, 4); //<>内是模闆參數
	double arr2[4] = { 1.1, 2.4, 1.6, 8.6 };
	double result2 = find_max <double>(arr2, 4);

	return 0;
}
           

多個模闆參數

#include "stdafx.h"
#include <stdio.h>

template <typename _A, typename _B, typename _C>
_C Sum(_A a, _B b)
{
	return a + b;
}

int main()
{
	double a = Sum<int,int,double>(1, 2);

	return 0;
}
           

繼續閱讀