C++ Template之函数模版

函数模版的定义:

template <typename T>
T const& max(const T& a,const T b)
{
	return a > b ? a:b;
}

int main()
{
	return 0;
}

 函数模版的使用:

#include <iostream>
#include <string>
using namespace std;

template <typename T>
T const& max(const T& a,const T b)
{
	return a > b ? a:b;
}

int main()
{
	int i = 7;
	cout << max(34,7) <<endl;
	double j = 10.9;
	cout << max(2.4,j) <<endl;
	string s1 = "mathematics";
	string s2 = "math";
	cout << max(s1,s2)<<endl;
	return 0;
}

 函数模版参数的推断

 模版参数有显式指定和隐式推断两种,显示的不可以进行类型转换,隐士的不能进行类型转换,类型必须唯一。

函数模版参数不能指定模版实参,这点和类模版不同。

模版函数重载

相同的情况下,先调用非模版函数

如果模版函数有一个最佳的匹配则调用模版函数。

显示指定空的模版参数列表指定从函数模版推导。

posted @ 2013-07-24 07:56  l851654152  阅读(275)  评论(0编辑  收藏  举报