C++学习 函数重载和函数模板
函数模板
Defining a function template follows the same syntax as a regular function, except that it is preceded by the template keyword and a series of template parameters enclosed in angle-brackets <>:
template <typename T> function-declaration
or
template <class T> function-declaration
For example, a generic sum function could be defined as:
template <class SomeType>
SomeType sum (SomeType a, SomeType b)
{
return a+b;
}
注:
1.类型参数可以不只一个,例如
template <class T1, typename T2>
2.这里关键字class和typename的作用相同,都表示类型名
3.类型名T也可以使用其他标识符,如SomeType, T较为常用
4.line1: template <class SomeType>后不能加分号
Instantiating a template is applying the template to create a function using particular types or values for its template parameters. This is done by calling the function template, with the same syntax as calling a regular function, but specifying the template arguments enclosed in angle brackets:
name <template-arguments> (function-arguments)
For example, the sum function template defined above can be called with:
k = sum<int> (10,20);
h = sum<double> (10.0,20.0);
注:
1.可简写为
k = sum (10,20);
h = sum (10.0,20.0);
2.简写的前提在于调用函数时不会造成歧义,如果函数调用时参数类型不同,编译器可能无法自动判断T,如sum(10,20.0)
// function template
#include <iostream>
using namespace std;
template <class T>
T sum(T a, T b)
{
T result;
result = a + b;
return result;
}
int main () {
int a=5;
double b=2.1;
// cout<<sum(a,b)<<endl; //error: no matching function for call to 'sum(int&, double&)',deduced
//conflicting types for parameter 'T' ('int' and 'double')
// cout<<sum(5,2.1)<<endl; //同上
// cout<<sum<int,double>(a,b)<<endl; //error: no matching function for call to 'sum(int&, double&)',
//error: wrong number of template arguments (2, should be 1)
cout<<sum<int>(a,b)<<endl; //OK,output:7
cout<<sum<double>(a,b)<<endl; //OK,output:7.1
return 0;
}
浙公网安备 33010602011771号