zhiyinjixu

  博客园  :: 首页  ::  :: 联系 ::  :: 管理

一般函数模板的书写格式:

template < 函数模板形参列表>

返回类型 函数名 (函数形参列表)

{

函数体

}

 

函数模板的特化的完整书写格式:

template < >

返回类型   函数名   <模板实参列表>  (函数形参列表)      //比起一般函数模板的书写格式来,多了  <模板实参列表> 

{

函数体

}

 

当模板的返回类型和函数形参的类型相同的时候,模板实参列表可以省略:

template < >

返回类型   函数名    (函数形参列表)   //比起函数模板的特化的完整书写格式来少了 <模板实参列表> ,和一般函数书写模式大致相同了

{

函数体

}

 

 

函数模板的特化的完整书写格式的示例代码:

#pragma once
#include <iostream>
#include <string.h>
using namespace std;

template <typename T1>
void And (T1 x, T1 y)
{
cout<< (x+y)<<endl;
}

template <>
void And <char *> (char s1[], char s2[])
{
cout<< strcat(s1,s2)<<endl;
}
int main()
{
double x=2.3,y=5.99;
And <double> (x,y);
char s1[] = "hello";
char s2[] = "world";
And(s1,s2);
}



当模板的返回类型和函数形参的类型相同的时候,模板实参列表可以省略的示例代码:

#pragma once
#include <iostream>
#include <string.h>
using namespace std;

template <typename T1>
T1 And (T1 x, T1 y)
{
return (x+y);
}

template <>
char * And (char s1[], char s2[]) //这里省略了函数模板实参列表,写成完整格式是这样的: char * And <char *> (char s1[], char s2[])
{
return strcat(s1,s2);
}

int main()
{
double x=2.3,y=5.99;
cout<<And <double> (x,y)<<endl;
char s1[] = "hello";
char s2[] = "world";
cout<<And(s1,s2)<<endl;
}



 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2011-11-14 15:29  zhiyinjixu  阅读(192)  评论(0)    收藏  举报