C++ 模板

1、模板函数


  格式一:

             template <class identifier> function_declaration;

 格式二:
             template <typename identifier> function_declaration;

eg:
	template<typename T>//equals to "template<class T>"
	T maxValue(T a,T b)
	{
		return (a > b?a:b);
	}

2、模板类


template<typename T>
class MyPair
{
private:
	T first;
	T second;
public:
	MyPair(T first,T second);
	~MyPair(void);
	void display();
};

template<typename T>
MyPair<T>::MyPair(T f,T s):first(f),second(s)
{
}

template<typename T>
void MyPair<T>::display()
{
	std::cout<<"first:"<<first<<"\t second:"<<second<<endl;
}

template<typename T>
MyPair<T>::~MyPair(void)
{
}
3、模板实例化

1)模板函数实例化

template<typename T>
T maxValue(T a,T b)
{
	return (a > b?a:b);
}

template<> int maxValue<int>(int a,int b)
{
	return (a>b?a:b);
}

2)模板类实例化

template<typename T>
class MyPair
{
private:
	T first;
	T second;
public:
	MyPair(T f,T s):first(f),second(s){ }
	~MyPair(void){ }
	void display()
	{
		std::cout<<"first:"<<first<<"\t second:"<<second<<endl;
	}
};


template<> class MyPair<int>
{
private:
	int first;
	int second;
public:
	MyPair(int f,int s):first(f),second(s)
	{
		std::cout<<"Constructor of explicit template class is called!"<<std::endl;
	}
	~MyPair(void){ }
	void display()
	{
		std::cout<<"first:"<<first<<"\t second:"<<second<<std::endl;
	}
};
4、非类型参数模板

1)普通变量

#include<iostream>
template<typename T,int N>//普通变量
class Container
{
private:
	T items[N];
	int count;//the number of all items
public:
	Container():count(0){ };
	~Container(){ };
	void add(T item)
	{
		if(count < N)
		{
			items[count] = item;
			count++;
		}
		else 
		{
			std::cout<<"The container is full now!"<<std::endl;
		}
	}
};

2)数组长度(数组引用)

#include<iostream>
using namespace std;
template<size_t N>//数组长度(数组引用)
void  display(int (&arr_ref)[N])
{
	for(int i=0;i<N;i++)
	{
		cout<<arr_ref[i]<<"\t";
	}
	cout<<endl;
}

int main()
{
	int arr[] = {1,2,3,4,5};

	display(arr);//the same effect to display<5>(arr)
	
	return 0;
}
5、模板与多文件工程

       随着工程的的增大,项目的代码经常放置于不同的文件中,通常将类或函数的声明与定义分开,如:声明放置于.h头文件,定义放置于.cpp源文件中。
       因为模板函数需要在编译时生成的具体函数,所以模板函数或模板类的声明与定义必须在一起,即位于同一个文件中。
       通常情况下,在一个项目中,一个函数的定义只能有一份,但模板函数是一个特例,即当项目中有多个模板函数的定义时,不会出现链接错误。

6、参考


      [1] Templates - C++ Documentation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值