C++提供了函数模板(function template)。所谓函数模板,实际上是建立一个通用函数,其函数类型和形参类型不具体指定,用一个虚拟的类型来代表。这个通用函数就称为函数模板。
凡是函数体相同的函数都可以用这个模板来代替,不必定义多个函数,只需在模板中定义一次即可。在调用函数时系统会根据实参的类型来取代模板中的虚拟类型,从而实现了不同函数的功能。
// 1.cpp : 定义控制台应用程序的入口点。
//
//
#include "stdafx.h"
#include "stdlib.h"
#include <Windows.h>
#include "assert.h"
int find(int array[], int length, int value)
{
//参数判断
if(NULL == array || 0 == length)
return FALSE;
int index = 0;
for (; index < length; index++)
{
if (array[index] == value)
{
return index;
}
}
return FALSE;
}
template<typename type>
int find1(type array[], int length, type value)
{
if (0 ==length || NULL == array)
{
return FALSE;
}
type *start = array;
type *end = array+length;
while(start < end)
{
if (value == *start)
{
return (((int)start-(int)array)/sizeof(type));
}
start++;
}
return FALSE;
}
static void test1()
{
int array[10] = {1,2};
assert(0 == find(array, 10, 1));
assert(FALSE == find(array, 10, 10));
}
int _tmain(int argc, _TCHAR* argv[])
{
test1();
return 0;
}
思考:数组与指针操作之“+”