Template function 函数模板用法

#include<iostream>
using namespace std;

const double PI = 3.1415926;

template <class T>
T min(T a[], int n){
	int i;
	T minv = a[0];
	for (i = 1; i < n; i++){
		if (a[i] < minv)
			minv = a[i];
	}
	return minv;
}

template<class T1>
double Circle_Square(T1 x){
	cout << "From template function";
	return x*x*PI;
}

double Circle_Square(long x){
	cout << "From long type function";
	return x*x*PI;
}

int main(){
	int a[] = { 2, 4, 1, 5, 6, 87, 5, 5, 6 };
	double b[] = { 2.33, 4.01, 3.0, 1.011 };
	cout << "min of a[]: " << min(a, 9) << endl;
	cout << "min of b[]: " << min(b, 4) << endl;

	int r1 = 1;  
	double r2 = 2.0;
	long r3 = 3;     //use the Overloaded functions if has, then refer to the template functions
	cout << " r1 " << Circle_Square(r1) << endl;
	cout << " r2 " << Circle_Square(r2) << endl;
	cout << " r3 " << Circle_Square(r3) << endl;
	int i;
	cin >> i;
	return 0;
}

Results:  

原文地址:https://www.cnblogs.com/bruceyo/p/3850126.html