1、函数模板:
#include<iostream>
using namespace std;
template<class type>
type tempfun(type x, type y)
{
return x+y;
}
int main()
{
cout<<tempfun(7,9)<<endl;
return 0;
}
对函数进行重载,实现对float类型参数进行相减操作。
#include<iostream>
using namespace std;
template<class type>
type tempfun(type x, type y)
{
return x+y;
}
template<>
float tempfun(float x, float y)
{
return x-y;
}
int main()
{ float a=7.8,b=6.8;
cout<<tempfun(a,b)<<endl;
return 0;
}
如果使用cout<<tempfun(7.8,6.8)<<endl;还是会调用正常没有特例化的模板。
2、类模板
定义、实例化类模板
#include<iostream>
using namespace std;
template <class T>
class temp{
public :
T temp_value;
public :
temp(T t)
{
temp_value = t;
}
public :
void display()
{
cout<<temp_value<<endl;
}
};
int main()
{
temp<int> a(5);
a.display();
return 0;
}
实例化时无论创建什么类型,只要能够实现构造函数中temp_value = t;语句就可以实现目的。
如果我想在当类的参数类型为float时,进行其他区别于模板的操作,可以进行对模板的特例化。
#include<iostream>
using namespace std;
class date{
public :
int x,y,z;
public :
date(int i, int j, int k)
{
x = i;
y = j;
z = k;
}
};
template <class T>
class temp{
public :
T temp_value;
public :
temp(T t)
{
temp_value = t;
}
public :
void display()
{
temp_value = temp_value * 10;
cout<<temp_value<<endl;
}
};
template<>
class temp<float>
{
public :
float temp_value;
public :
temp(float t)
{
temp_value = t * 2.0;
}
public :
void display()
{
cout<<"float:"<<temp_value<<endl;
}
};
int main()
{
temp<float> ftemp(2.3);
ftemp.display();
return 0;
}
当类型为float时,类的成员变量会翻倍,并且在输出时标明了“float”。
如果不想让成员变量翻倍,除了去掉哪一行代码这种方式,还可以只是特例化函数,也就是重构类模板中的函数,这个函数只有在<>中类型为自己指定的类型时才会被调用。
#include<iostream>
using namespace std;
class date{
public :
int x,y,z;
public :
date(int i, int j, int k)
{
x = i;
y = j;
z = k;
}
};
template <class T>
class temp{
public :
T temp_value;
public :
temp(T t)
{
temp_value = t;
}
public :
void display()
{
temp_value = temp_value * 10;
cout<<temp_value<<endl;
}
};
template<>
void temp<float>::display()
{
cout<<"float:"<<temp_value<<endl;
}
int main()
{
temp<float> ftemp(2.3);
ftemp.display();
return 0;
}