C++那.事,模板

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值