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
- C++ template模板函数的定义与调用
- C++ Template学习笔记之函数模板(1)——函数模板定义
- C++ Template学习笔记之函数模板(1)——函数模板定义
- C/C++函数模板template
- C++,template,类模板和函数模板
- 函数的定义与调用
- 函数的定义与调用
- (一)函数模板与类模板 Template
- template模板的声明及定义
- 模板类中友元函数的声明与定义
- C++Template学习笔记之函数模板
- 函数模板 Function Template(C++Primer-10)
- 函数模板template-重载的模板
- [C#]调用字符串中定义的函数
- 《Essential C++》泛型之 模板函数 Template Functions 与 重载函数 Overloaded Functions
- 过程、函数的定义与调用
- 第十一周 函数的定义与调用
- 九、函数的定义与调用
- es6笔记7^_^class_0
- 【t032】地理
- DEEPLEARNING.UNIVERSITY深度学习论文库
- 10.5.3
- 10.6
- C++ template模板函数的定义与调用
- day18IO概述& 字符流FileWriter FileReader
- 五种开源协议的比较(BSD,Apache,GPL,LGPL,MIT)
- 这就是生活!
- 基本数据类型
- Event(事件)的传播与冒泡
- BZOJ 1068: [SCOI2007]压缩 划分DP,记忆化搜索
- 目录 (GNC) (pb-ds)
- opencv学习之仿射变换