C++ template模板函数的定义与调用

来源:互联网 发布:网络流量监视软件 编辑:程序博客网 时间:2024/06/12 07:27

引用《C++primer(第四版)》里的观点:
1)标准C++为编译模板代码定义了两种模型:“包含”模型和“分别编译”模型。
2)所有编译器都支持“包含”模型,某些编译器支持“分别编译”模型。

问题的提出:(帖子在:http://topic.csdn.net/u/20101215/15/f4f270f2-f0f9-4c5f-8765-1bfde2aeebbf.html)

方法一:

声明和实现都放在头文件里。

在类模板头文件template_compile.h中:

template<class T>  class base  {  public:      base() {};      ~base() {};      T add_base(T x,T y);  };  template<class T>  T base<T>::add_base(T x,T y)  {      return x+y;  } 

在使用模板的测试文件use_template.cpp中:

#include<iostream>  #include "template_compile.h"  using namespace std;  void main()  {      base<int> bobj;      cout<<bobj.add_base(2,3)<<endl;  }  

方法二:

按C++primer中的“包含”模型,在定义模板类的头文件中的末行用语句:#include “template_compile.cpp”

在类模板头文件template_compile.h中:

template<class T>  class base  {  public:      base() {};      ~base() {};      T add_base(T x,T y);  };  #include "template_compile.cpp"  

在类模板的实现文件template_compile.cpp中:

template<class T>  T base<T>::add_base(T x,T y)  {      return x+y;  } 

测试文件不变。

方法三

使用define

在类模板头文件template_compile.h中:

template<class T>  class base  {  public:    base() {};    ~base() {};    T add_base(T x,T y);  };  #define TEMP  #include "template_compile.cpp"  

在类模板的实现文件template_compile.cpp中:

#ifdef TEMP  template<class T>  T base<T>::add_base(T x,T y)  {    return x+y;  }  #endif  

测试文件不变。

方法四

在类模板头文件template_compile.h中:

template<class T>  class base  {  public:      base() {};      ~base() {};      T add_base(T x,T y);  };

在类模板的实现文件template_compile.cpp中:

#include "template_compile.h"  template<class T>  T base<T>::add_base(T x,T y)  {      return x+y;  }  

在使用模板的测试文件use_template.cpp中:使用#include “template_compile.cpp”

#include<iostream>  #include "template_compile.cpp"  using namespace std;  void main()  {      base<int> bobj;      cout<<bobj.add_base(2,3)<<endl;  }  
2 0