Function template

A function template is a type-independent function that can be used as a pattern to produce a specific type version of a function.

int abs( int x ){ 
	return x<0?-x:x; 
}
double abs( double x ){ 
	return x<0?-x:x; 
}

Using function templates, you can design general-purpose functions. These functions are independent of types and are automatically instantiated only when needed, thereby forming a "batch-type" programming method.
The syntax form of the function template definition is:

template<模板形参表>返回类型 函数名(形参列表)
{
	函数体
}
template<typename T>
T abs(T x){ 
	return x<0?-x:x; 
}
int main(){ 
	int n=-5; 
	double d=-5.5;
	cout<<abs(n)<<,<<abs(d)<<endl;
	return 0;
}

► The template parameter list (template parameter list) is a list of one or more template parameters enclosed by a pair of angle brackets <>. It is not allowed to be empty. The parameters are separated by commas. There are two forms .
► ① The first form
typename type parameter name 1, typename type parameter name 2,…
► ② The second form
class type parameter name 1, class type parameter name 2,…

Function template example

include <iostream>
using namespace std;
template <class T> T add(T a,T b){
	return a+b;
}
int main(){
	cout<<"int_add="<<add(10,20)<<endl; //生成整型版本的add函数
	cout<<"double_add="<<add(10.2,20.5)<<endl;//生成实型版本的add函数
	cout<<"char_add="<<add('A','\2')<<endl;//生成字符型版本的add函数
	cout<<"int_add="<<add(100,200)<<endl;
	return 0;
}
Published 19 original articles · Like9 · Visits 2900

Guess you like

Origin blog.csdn.net/u013031697/article/details/104548364