函数模板的载体-HPP

时间:2021-08-06 10:07:14

在C++中,我们通常将声明放在.h头文件中,将具体的实现代码放在.cpp文件中。但是函数模板通常不这么做,函数模板是将其声明和实现都放在.hpp文件中。hpp是Header Plus Plus的缩写,是专门存放模板文件的格式。可能有人会问,为什么要将函数模板的声明和实现放在一个头文件中?这是因为当编译器读到函数模板的实现时,因为没有具体的模板参数,所以还不能为它创建一个函数实例,只有当使用这个函数模板的时候,才会为它创建一个具体的函数实例;所以,对于编译器而言,函数模板的实现其实也是一种声明,是声明如何构建一个模板函数的方法。

在前面的几章中,我们都是将函数模板和主函数放到了一个cpp文件中,但是在实际的工作中,都是将函数模板和主函数相分离的。今天,我们就使用HPP文件来实现函数模板和主函数相分离的目标。

例1 使用HPP文件实现模块化编程

Add.hpp文件

#ifndef _ADD_HPP_
#define _ADD_HPP_
template<typename T>
T Add(T t1, T t2)
{
return t1 + t2;
}
#endif

主文件

#include<iostream>
#include "Add.hpp"
using namespace std;
void main()
{
int nRet = Add<int>(1,2);
cout << "和:" << nRet << endl;
}

运行效果如图1所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAqUAAABbCAIAAADFvWslAAAL1klEQVR4nO2d7W8cRwGH/efcH+Dv/mhhBBxKDUSosuFUqUEICVlUAoEsQKhpQ1rauuIcSENSmkYmJJyvUZymcc6uoKZJpdrUJcECekVqq8bvDrVNP5gP57ubt52dvdu9uRs/jx5V9t3uzsu685vZ3bv0zUzmERERMWz7ZibzmwsnEBERsWXfyue7wajqkfeIiIgp6D3pyXtERMTM9Z705D0iImLmek968h4RETFzvSc9eY+IiJi53pOevEdERExgzkrUXt6TnrxHRERMYIfz/uDg4ODgwP5K5/J+4U9P3Lj4QxffuvqD9b887v1sISIitqYl1DNa34sB307Yp5D3l69O3313+e6772kuv7O4/M7i8vSN+emZuemZuYtTV/5941vezxaGbbmQyxWGvVcjY0cmBnO5waEl/zVJbLnQczXv4d7G1O183jdivs2wTyHvZytze/v7u3sx7u3v35ydu/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YY9kVUHbxXDAAAegj/eQ8AAABZQ94DAACED3kPAAAQPuQ9AABA+JD3AAAA4UPeAwAAhI+S96Ojo0q666+Q9wAAAD2GnvdiwCu/kvcAAAA9iTHvaxkv/kzeAwAA9DD6/ftRGe7fAwAA9DzG5/UsYU/eAwAA9B5Rz+dHhT15DwAA0HvweTwAAIDwIe8BAADCh7wHAAAIH/IeAAAgfDqd94iIiNgrtpj3iIiIGIDkPSIiYviS94iIiOFL3iMiIoYveY+IiBi+5D0iImL4kveIiIjhS94jIiKG72HeIyIiYtj+H1fZgNDu3wN7AAAAAElFTkSuQmCC" alt="" />

图1 使用HPP文件实现模块化编程

例1中,我们首先在Add.hpp文件中创建了一个函数模板Add.hpp,之后在主文件中使用include包含Add.hpp文件,这样就可以实现函数模板和主函数的分离效果了,也就是所谓的模块化编程思想。

今天我们主要讲述了函数模板的载体和在实际的工作中,如何将函数模板和主函数分离的方法,从而实现模块化编程的目标。大家可以回去实践一下,加深体会。