C++高级编程(五)模板

模板:属于泛型编程,泛型编程指的是代码“重用”,固定的代码但是其内部函数、对象类型或类可以不同。

1、函数模板

函数模板的声明形式为:

template

<返回类型><函数名>(参数表)

{

    函数体

}

#include


using namespace std;

template
void add(T a, Y b)
{
	cout <<(int)a<<"+"<<(int)b<<"=" << a + b << endl;
}



int main()
{
	int a = 1;
	char b = '2';
	double c = 3.0;
	add(a, b);
	add(a,c);
	add(c, b);


	system("pause");
	return 0;
}

typename改为class也是可以的。

类模板:

用vector写栈

//栈:先进后出,后进先出
#include 
#include 
#include 


using namespace std;

template
class Stack{

private:
	vector elems;

public:
	void push(T const&);// 入栈
	void pop();// 出栈
	T top()const;// 返回栈顶元素
	bool empty()const{// 如果为空则返回真。
		return elems.empty();
	}
};

// 追加传入元素的副本
template
void Stack::push(T const&elem)
{
	elems.push_back(elem);
}

// 删除最后一个元素
template
void Stack::pop()
{
	if (elems.empty())
	{
		throw out_of_range("Stack<>::pop():empty stack");
	}
	else
		elems.pop_back();
}

// 返回最后一个元素的副本 
template
T Stack::top()const
{
	if (elems.empty())
		throw out_of_range("Stack<>::top():empty stack");
	return elems.back();
}

int main()
{
	try{
		Stack intstack;
		Stack stringstack;
		intstack.push(7);
		cout << intstack.top() << endl;

		stringstack.push("hello");
		cout << stringstack.top() << endl;

		intstack.pop();
		stringstack.pop();

	}
	catch (exception const&e)
	{
		cerr << "Exception:" << e.what() << endl;
		return -1;
	}

	system("pause");
	return 0;
}
参考: 模板函数与函数模板
参考: 模板类与类模板












你可能感兴趣的:(C++,C/C++)