C++ — 模板的详解


我们经常听到C++,模板这个概念。就我自己的理解,模板其实就是为复用而生,模板就是实现代码复用
机制的一种工具,它可以实现类型参数化,即把类型定义为参数,从而实现了真正的代码可重用性。模版
可以分为两类,一个是函数模版,另外一个是类模版。

举个最简单的例子,当你编写一个交换int型的swap函数,当你要交换double就得重新写一个,这里就尴尬
了。使用模板的目的就是要让这程序的实现与类型无关,比如一个swap模板函数,即可以实现int 型,又可
以实现double型的交换

注意:模板的声明或定义只能在全局,命名空间或类范围内进行。即不能在局部范围,函数内进行,比如不
在main函数中声明或定义一个模板。

函数模板格式:

 template <class 形参名1class 形参名2, class 形参名n
  返回类型 函数名(参数列表)
 {...}

模板形参的定义既可以使用class,也可以使用typename,含义是相同的。

现在我们来实现第一个模板程序:


#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;

template<typename T>
bool IsEqual(const T& left, const T& right)
{
	return left == right;
}
void test1()
{
	string s1("s1"), s2("s2");
	cout<< IsEqual(s1, s2)<< endl;
	cout<< IsEqual(1, 1)<< endl;
}
int main()
{
	
	test1();
	system("pause");
	return 0;
}

我们来看看运行结果,有没有觉得这样程序写起来很方便。



我们再从汇编的角度上来看:


                                  模板参数匹配及显示实例化


现在我们继续往下走,不知道我们有没有见过这样的形式:

就是调用一个模板函数的时候,在函数名后面加上<类型>,这时候系统不需要从形参这里推断类型了。

直接使用尖括号里面的类型就可以了。
  
返回类型 函数名<类型>(参数列表)

记住这种形式,接下来我们来验证一下。
<span style="font-family: SimHei; font-size: 14px;">template<typename T>
bool IsEqual(const T& left, const T& right)
{
	return left == right;
}
void test1()
{
	cout << IsEqual(1, 1) << endl;
	cout << IsEqual<int>(1, 1.2) << endl;        // 显示实例化
	cout << IsEqual<double>(1, 1.2) << endl;     // 显示实例化
}

int main()
{
	
	test1();
	system("pause");
	return 0;
}</span>
压根就编不过去,记住了! 这里当只有一个模板参数时,不要出现类型不同的定义。编译器不允许。


                                           模板类



模板类的意思跟模板参数差不多吧,让程序员不用写跟类型有关的代码。

模板类的形式:

               template<class 形参名1class 形参名2, ...class 形参名n>  
               class 类名
               { ... };

类模板和函数模板都是以template开始后接模板形参列表组成,模板形参不能为空一但声明了类模板

就可以用类模板的形参名声明类中的成员变量和成员函数,即可以在类中使用内置类型的地方都可以使

用模板形参名来声明比如

       template<class T> class A{public: T a; T b; T hy(T c, T &d);};

在类A中声明了两个类型为T的成员变量ab,还声明了一个返回类型为T带两个参数类型为T的函数hy


类模板对象的创建:比如一个模板类A,则使用类模板创建对象的方法为A<int> m;在类A后面跟上一个

<>尖括号并在里面填上相应的类型,这样的话类A中凡是用到模板形参的地方都会被int 所代替。当类

模板有两个模板形参时创建对象的方法为A<int, double> m;类型之间用逗号隔开。


对于类模板,模板形参的类型必须在类名后的尖括号中明确指定。举个例子A<1> m; 这样是绝对不行的

,记住类模板中不存在实参类型的推断。


在类模板外部定义成员函数的方法为:

    template<模板形参列表> 函数返回类型 类名<模板形参名>::函数名(参数列表){函数体},

比如有两个模板形参T1T2的类A中含有一个void h()函数,则定义该函数的语法为:

    template<class T1,class T2> void A<T1,T2>::h(){}。

注意:当在类外面定义类的成员时template后面的模板形参应与要定义的类的模板形参一致。


下面是我用模板写的一个简易的链表:

<span style="font-family: SimHei; font-size: 14px;">template<class T>
struct ListNode
{
	ListNode<T>* _next;
	ListNode<T>* _prev;
	T _date;

	ListNode(const T& x)
		:_data(x)
		, _next(NULL)
		, _prev(NULL)
	{}
};

template<class T>
class List
{
	typedef ListNode<T> Node;
public:
	List()
		:_head(NULL)
		, _tail(NULL)
	{}

	List(const List<T>& l)
		:_head(NULL)
		, _tail(NULL)
	{
		Node* cur = l._head;
		while (cur)
		{
			PushBack(cur->data);
			cur = cur->_next;
		}
	}
	List<T>& operator=(List<T> l)
	{
		Swap(l);
		return *this;
	}

	void Swap(List<T>& l)
	{
		swap(_head, l._head);
		swap(_tail, l._tail);
	}
	~List()
	{
		Clear();
	}
	void clear()
	{
		Node* cur = _head;
		while (cur)
		{
			Node* next = cur->_next;
			delete cur;
			cur = next;
		}
		_head = _tail = NULL;
	}
	void PushBack(cinst T& x)
	{
		if (_head == NULL)
		{
			_head = _tail = new Node(x);
		}
		else{
			Node* tmp = new Node(x);
			_tail->_next = tmp;
			tmp->_prev = _tail;
			_tail = tmp;
		}
	}
	void PopBack()
	{
		if (_head == NULL)
		{
			return;
		}
		else if (_head == _tail)
		{
			delete _tail;
			_head = _tail = NULL;
		}
		else
		{
			Node* prev = _tail->_prev;
			delete _tail;
			_tail = prev;
			_tail->_next = NULL;
		}
	}

	void PushFront(const T& x)
	{
		assert(_head != NULL);
		if (_head == NULL)
		{
			PushBack(x);
		}
		else
		{
			Node* cur1 = new Node(x);
			cur1->next = _head;
			_head->_prev = cur1;
			_head = cur1;
		}
	}

	PopFront()
	{
		if (_head == NULL)
		{
			return;
		}
		else if (_head == _tail)
		{
			delete _head;
			_head = _tail = NULL;
		}
		else
		{
			Node* next = _head->_next;
			delete _head;
			_head = next;
		}
	}

	T& Front()
	{
		assert(_head);
		return _head->_date;
	}

	T& Back()
	{
		assert(_tail);
		return _tail->_date;
	}
	size_t Size()
	{
		size_t count = 0;
		Node* cur = _head;
		while (cur)
		{
			++count;
			cur = cur->_next;
		}
		return count;
	}

	bool Empty()
	{
		return NULL == _head;
	}

	void Insert(Node* pos, const T& x)
	{
		asert(pos != NULL);
		if (NULL == _head)
		{
			PushBack(x);
		}
		else if (_head == _tail || pos == _head)
		{
			PopBack(x);
		}
		else
		{
			Node* cur = new Node(x);
			Node* cur2 = pos->_next;
			cur2->_prev = pos;
			cur->_next = cur2;
			pos->_next = cur;
			cur->_prev = pos;
		}
	}

	void Erase(Node* pos)
	{
		assert(_head != NULL);
		if (_head == _tail)
		{
			PopFront();
		}
		else
		{
			Node* cur = _head;
			while (cur->_next != pos)
			{
				cur = cur->_next;
			}
			Node* del = pos;
			cur->_next = pos->_next;
			pos->_next->_prev = cur;
			delete del;
		}
	}

	Node* Find(const T& x)
	{
		Node* cur = _head;
		while (cur)
		{
			if (cur->_date == x)
			{
				return cur;
			}
			cur = cur->_next;
		}
		return 0;
	}

	void Print()
	{
		Node* cur = _head;
		while (cur)
		{
			cout << cur->_date << " ";
			cur = cur->_next;
		}
		cout << endl;
	}

protected:
	Node* _head;
	Node* _tail;

};
</span>



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值