C++中的模板(二)

cpp 复制代码
template<typename T1,typename T2>//这里的typename也可以替换成class
T1 Func(const T1& a,const T2& b){//也可以有返回值
cont<<a<<""<<b<<endl;
}
//实例化推演出具体的函数
int main(){

Func(x,y);
}
cpp 复制代码
template<typename T>
Add(const T& a,const T& b){/const 放置权限被放大
return a+b;
}

int main(){
//实参传递的类型,推演T 的类型
double x=1.2,y=2.3;
int s=1,z=9;
count<<Add((int)x,z)<<endl;
count<<Add(x,(double)z)<<endl;
//显式实例化
count<<<int>Add(a,z)<<endl;
count<<<double>Add(a,z)<<endl;
}
cpp 复制代码
template<ttypename T>
T* Alloc(int n)
{
    return new T[n];
}

int main(){
 // 有些函数无法自动推,只能显示实例化
   double* p1 = Alloc<double>(10);
return 0;
}

类模板

cpp 复制代码
// 类模板
template<class T>
class Stack
{
public:
	Stack(size_t capacity = 3);

	void Push(const T& data);

	// 其他方法...

	~Stack()
	{
		if (_array)
		{
			free(_array);
			_array = NULL;
			_capacity = 0;
			_size = 0;
		}
	}

private:
	T* _array;
	int _capacity;
	int _size;
};

int main()
{
	Stack<int> s1;    // int
	Stack<double> s2; // double
	Stack<char> s3;   // char

	return 0;
}


template<class T>
Stack<T>::Stack(size_t capacity)
{
	/*_array = (T*)malloc(sizeof(T) * capacity);
	if (NULL == _array)
	{
		perror("malloc申请空间失败!!!");
		return;
	}*/
	_array = new T[capacity];

	_capacity = capacity;
	_size = 0;
}

template<class T>
void Stack<T>::Push(const T& data)
{
	// CheckCapacity();
	_array[_size] = data;
	_size++;
}
template<class T>
void Stack<T>::Push(const T& data)
{
	// CheckCapacity();
	_array[_size] = data;
	_size++;
}

int main()
{
	Stack<int> s1;    // int
	Stack<double> s2; // double
	Stack<char> s3;   // char

	return 0;
}
复制代码

// 普通类,类名和类型是一样

// 类模板,类名和类型不一样

// 类名:Stack

// 类型:Stack<T>

相关推荐
小糖学代码1 分钟前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
handler019 分钟前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
geBR OTTE14 分钟前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu19 分钟前
博客系统UI自动化测试报告
java
小白学大数据38 分钟前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调1 小时前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳1 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木1 小时前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***5441 小时前
如何在Dev-C++中使用Clang编译器
开发语言·c++
码界筑梦坊1 小时前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化