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>

相关推荐
yuniko-n5 分钟前
【JUC】JMM(Java 内存模型)
java·开发语言
十碗饭吃不饱6 分钟前
MySQL InnoDB RR 隔离下二级索引临键锁引发 INSERT 锁超时 全链路解析
java·数据库·mysql
专业程序开发源15 分钟前
springboot校企合作双选会一站式预约与面试系统16010-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·面试·php·课程设计
General_G25 分钟前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
syagain_zsx25 分钟前
protobuf 实战:从 .proto 到 C++ 序列化的完整链路
c++·学习·程序人生·谷歌·protobuf
Elastic 中国社区官方博客1 小时前
Observability:当 YAML 遇上 IConfiguration:OpenTelemetry .NET SDK 的声明式配置
大数据·开发语言·elasticsearch·搜索引擎·全文检索·.net
郑州光合科技余经理1 小时前
同城商城源码:商品库和订单库怎么随包交付
android·java·开发语言·后端·uni-app·php·ai编程
\光辉岁月/1 小时前
4.String类
java·面向对象·stringbuilder·string·stringbuffer·字符串类
welfare9621 小时前
新号别搞:C++_list
开发语言·c++
数据狐(Datafox)1 小时前
一文读懂京东商品详情 API:返回字段解读与 JSON 样例
开发语言·数据库·爬虫·json