C++模板函数、模板类小笔记

C++除了类里的内存模型比较有意思之外,泛型编程也是很有思想的抽象。当然最有用的还是标准模板库,带上标准的~里面包含了各种现成的容器,好用并且格式比较统一 美观~

模板函数

#include <iostream>
#include <string>
using namespace std;

template <typename Type>
const Type& GetMax(const Type& value1, const Type& value2){
	if(value1 > value2)
		return value1;
	else
		return value2;
}

int main(){
	int num1 = -101, num2 = 2011;
	int res = GetMax(num1, num2);
	cout << "Max : " << res << endl;
	return 0;
}

模板类

模板定义

模板实例化:使用一个或多个模板参数来创建特定的类型

模板具体化:使用特定的类型实例化模板时,需要显示地指定不同的行为。为特点的类型指定行为

#include <iostream>
using namespace std;

//模板定义
template <typename T1=int, typename T2=double>
class HoldsPair{
private:
	T1 value1;
	T2 value2;
public:
	HoldsPair(const T1& val1, const T2& val2):value1(val1), value2(val2){}
	const T1& GetFirstValue() const;
	const T2& GetSecondValue() const;
}

//模板具体化
template<> class HoldsPair<int, int>
{	
private:
	int value1;
	int value2;
	string strFun;
public:
	HoldsPair(const int& val1, const int& val2):value1(val1), value2(val2){}
	const int& GetFirstValue() const{
		cout << "Returning integer" << value1 << endl;
		return value1;
	}
};

int main(){
	HoldsPair<int, int> pairIntInt(222, 333);
	pairIntInt.GetFirstValue();
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值