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>

相关推荐
indexsunny4 分钟前
互联网大厂Java求职面试实战:Spring Boot微服务与Redis缓存场景解析
java·spring boot·redis·缓存·微服务·消息队列·电商
无心水6 分钟前
【分布式利器:腾讯TSF】7、TSF高级部署策略全解析:蓝绿/灰度发布落地+Jenkins CI/CD集成(Java微服务实战)
java·人工智能·分布式·ci/cd·微服务·jenkins·腾讯tsf
28岁青春痘老男孩5 小时前
JDK8+SpringBoot2.x 升级 JDK 17 + Spring Boot 3.x
java·spring boot
方璧5 小时前
限流的算法
java·开发语言
元Y亨H5 小时前
Nacos - 服务注册
java·微服务
Hi_kenyon6 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
曲莫终6 小时前
Java VarHandle全面详解:从入门到精通
java·开发语言
一心赚狗粮的宇叔6 小时前
中级软件开发工程师2025年度总结
java·大数据·oracle·c#
byxdaz6 小时前
C++内存序
c++