函数模板利用关键字 template 使用函数模板有两种方式:自动类型推导、显示指定类型 模板的目的是为了提高复用性,将类型参数化## 自动类型推导
自动推导类型
template < typename T >
void myvalue ( T & a, T & b)
{ T temp = a; a = b; b = temp;
}
float a = 2 ;
float b = 3 ;
myvalue ( a, b) ;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
显示指定类型
myvalue < float > ( a, b) ; cout << "a = " << a << endl; cout << "b = " << b << endl;
# define _CRT_SECURE_NO_DEPRECATE
# include <iostream>
using namespace std; void int_value ( int & a, int & b)
{ int temp = a; a = b; b = temp;
} void float_value ( float & a, float & b)
{ float temp = a; a = b; b = temp;
}
template < typename T >
void myvalue ( T & a, T & b)
{ T temp = a; a = b; b = temp;
} void test1 ( )
{ float a = 2 ; float b = 3 ; myvalue ( a, b) ; cout << "a = " << a << endl; cout << "b = " << b << endl; myvalue < float > ( a, b) ; cout << "a = " << a << endl; cout << "b = " << b << endl;
}
int main ( )
{ test1 ( ) ; return 0 ;
}