模板简单定义

定义模板函数:

templateTest.h

#include "stdafx.h"
using namespace std;

 template<typename T>
 
 T const AddTem(T const a,T const b)
 {
	 return a + b;
 }

 template<typename T2>
 void swaps(T2& a,T2& b)
 {
	 T2 temp;
	 temp = a;
	 a = b;
	 b = temp;
 }

 template<typename T3>
 void print(const T3  &a, T3 const &b)
 {
	 cout<<endl<<"使用模板后, a="<<a<<"  b="<<b<<endl;
 }
若把template<typename T> 与后边的两个template写在一块儿,编译时会出错

使用时直接调用:

int an = 3, bn = 4;
double ad = 5.3, bd = 2.3;
char ac = 'a', bc = 'b';
swap12(an, bn);
print(an, bn);

若函数模板重载,在templateTest.h中加上:

 template<typename T4>
T4 const AddIem(T4 const a, T4 const b, T4 const c)
 {
	 return a + b + c;
 }

同理,类模板的定义:

 template<typename T5>
 struct Node
 {
	 Node(T5 &d):c(d),next(0),pref(0){}
	 T5 c;
	 Node *next, *pref;
 };

 template<typename T6>
 class List
 {
	 Node<T6> *first, *last;
 public:
	 List(){first = nullptr,last = nullptr};
	 void add(){}
	 ~List(){};
 };
写的时候,类定义最后的’;‘号忘了,编译时报错位置定位在cpp文件上,说第一个函数void前缺少’;‘templateTest.h刚好在此函数前边,应该是编译顺序的问题吧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值