显示特化:
template<>
void fun<const int&>(const int& i)
{
cout << i << endl;
}
#include<iostream>
#include<assert.h>
#include<vector>
using namespace std;
template<class T>
void fun(T *t,int begin,int end,double sum)
{
for(int i=begin;i<end;i++){
sum+=t[i];
}
cout << sum << endl;
}
//中间的<>只要放T的类型就可以了
template<>
void fun<double>(double d[],int begin,int end,double sum)
{
for(int i=begin;i<end;i++){
sum+=d[i];
}
cout << sum << endl;
}
template<>
void fun<int>(int d[],int begin,int end,double sum)
{
for(int i=begin;i<end;i++){
sum+=d[i];
}
cout << sum << endl;
}
int main()
{
double arr1[20];
int arr2[20];
for(int i=0;i<20;i++){
arr1[i]=(i+0.1);
arr2[i]=i;
}
fun(arr1,1,10,0);
fun(arr2,1,10,0);
}
45.9
45
#include<iostream>
using namespace std;
template<typename T>
int f(T){
return 1;
}
template<typename T>
int f(T*){
return 2;
}
//f(T)的特化
template<>
int f(int){
cout << "f(T)" << endl;
return 3;
}
//f(T*)的特化
template<>
int f(int *){
cout << "f(T*)" << endl;
return 4;
}
template<typename T>
int g(T,T x=42){
return x;
}
/*
template<>
int g(int x,int y=42){//这里不能包含缺省实参值
cout << "g(int x,int y=42)" << endl;
return x/y;
}
*/
template<>
int g(int x,int y){
cout << "g(int x,int y)" << endl;
return x/y;
}
int main()
{
int *i;
f(i);
g(1,2);
}
f(T*)
g(int x,int y)