第一章
函数模板
本章主要介绍函数模板,即那些为了代表了一系列函数而被参数化(parameterized)的函数。
1.1 初识函数模板
函数模板提供了可以被不同类型调用的函数行为。简单来说,函数模板代表的是一类函数。它看起来就像普通的函数一样,不同的是函数中的一些元素并没有被定义:这些参数就是被参数化的。为了说明这点,我们来看个简单的例子。
basics/max1.hp
template<typename T> T max(T a,T b) { //if b < a then yield a else yield b //如果b小于a则返回a,不然就返回b。即返回a和b中的最大值 return b < a ? a : b; }
个人笔记
参数化(parameterized):
大致意思就是,将我们可能用到的变量用某个参数表示,等到实际运行的时候我们再根据情况给予参数特定的值,让这个变量符合当前的运行环境。
?运算符:
如果"?"前的式子为真,返回":"前的值。反之返回后者。
return b < a ? a : b;
完整的max函数代码示例:
需要注意的是,<iostream>中已经自带max函数,所以如果你把函数也命名为max,编译器是不知道调用哪一个的。
#include<iostream>
using namespace std;
template <typename T>
T Max(T a,T b) //max -> Max
{
return a > b ? a : b;
}
int main()
{
int a = 1, b = 2;
cout<<Max<int>(a, b);
}