#include"stdafx.h"
#include<iostream>
using namespace std;
/**
函数模板
一个通用函数模板,该函数在数组中查找一个值并返回这个值得索引。
*/
static const size_t NOT_FOUND = (size_t)(-1);
template <typename T>
size_t Find(T& value, T* arr, size_t size)
{
for (size_t i = 0; i < size; i++)
{
if (arr[i] == value)
{
return i;
}
}
return NOT_FOUND;
}
/*
函数模板可以接受非类型的参数,与类模板一样。
前面的Find()函数的实现需要把数组的大小作为其一个参数。当编译器知道数组的确切大小,
例如,基于堆栈的数组。用这种数组调用Find()函数,就不需要传递数组的大小。
*/
template <typename T,size_t S>
size_t Find(T& value, T(&arr)[S])
{
return Find(value, arr, S);
}
/*
函数模板特例化 const char *C
*/
template <>
size_t Find<const char*>(const char*& value, const char** arr, size_t size)
{
cout << "Specialization" << endl;
for (size_t i = 0; i < size; i++)
{
if (strcmp(arr[i], value) == 0){
return i;
}
}
return NOT_FOUND;
}
int main()
{
int x = 3, intArr[] = { 1,2,3,4 };
size_t sizeIntArr = sizeof(intArr)/sizeof(int);
size_t res;
res = Find(x, intArr, sizeIntArr);//calls Find<int> by duduction
res = Find<int>(x, intArr, sizeIntArr);
if (res != NOT_FOUND){
cout << res << endl;
}
else {
cout << "Not found" << endl;
}
double d1 = 5.6, dArr[] = { 1.2,3.4,5.7,7.5 };
size_t sizeDoubleArr = sizeof(dArr)/sizeof(double);
res = Find(d1,dArr,sizeDoubleArr);//calls Find<double> by deduction
res=Find<double>(d1, dArr, sizeDoubleArr);//calls Find<double> explicitly
if (res!=NOT_FOUND)
{
cout << res << endl;
}
else {
cout << "Not found" << endl;
}
int x2 = 3, intArr2[] = { 1,2,3,4 };
size_t res2;
res2= Find(x2, intArr2);
cout << res2 << endl;
//特例化函数模板的使用
char* word = "Two";
char* arrStr[] = { "one","two","three","four" };
size_t sizeArr = sizeof(arrStr) / sizeof(arrStr[0]);
size_t res3;
res3 = Find<char*>(word, arrStr, sizeArr);
res3 = Find(word, arrStr, sizeArr); cout <<"Res3="<< res3<< endl;
return 0;
}
C++ 函数模板
最新推荐文章于 2024-08-07 16:33:34 发布
