C++中模板(Template)详解及其作用介绍

目录

  • 概述
  • 函数模板
  • 类模板
  • 模板类外定义成员函数
  • 类库模板
  • 抽象和实例

概述 模板可以帮助我们提高代码的可用性, 可以帮助我们减少开发的代码量和工作量.
C++中模板(Template)详解及其作用介绍
文章图片


函数模板 函数模板 (Function Template) 是一个对函数功能框架的描述. 在具体执行时, 我们可以根据传递的实际参数决定其功能. 例如:
int max(int a, int b, int c){a = a > b ? a:b; a = a > c ? a:c; return a; }long max(long a, long b, long c){a = a > b ? a:b; a = a > c ? a:c; return a; }double max(double a, double b, double c){a = a > b ? a:b; a = a > c ? a:c; return a; }

【C++中模板(Template)详解及其作用介绍】写成函数模板的形式:
templateT max(T a, T b, T c){a = a > b ? a:b; a = a > c ? a:c; return a; }


类模板 类模板 (Class Template) 是创建泛型类或函数的蓝图或公式.
#ifndef PROJECT2_COMPARE_H#define PROJECT2_COMPARE_Htemplate // 虚拟类型名为numtypeclass Compare {private:numtype x, y; public:Compare(numtype a, numtype b){x=a; y=b; }numtype max() {return (x>y)?x:y; }; numtype min() {return (x < y)?x:y; }; };

mian:
int main() {Compare compare1(3,7); cout << compare1.max() << ", " << compare1.min() << endl; Compare compare2(2.88, 1.88); cout << compare2.max() << ", " << compare2.min() << endl; Compare compare3('a', 'A'); cout << compare3.max() << ", " << compare3.min() << endl; return 0; }

输出结果:
7, 3
2.88, 1.88
a, A

模板类外定义成员函数 如果我们需要在模板类外定义成员函数, 我们需要在每个函数都使用类模板. 格式:
template函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {}

类模板:
#ifndef PROJECT2_COMPARE_H#define PROJECT2_COMPARE_Htemplate // 虚拟类型名为numtypeclass Compare {private:numtype x, y; public:Compare(numtype a, numtype b); numtype max(); numtype min(); }; templateCompare::Compare(numtype a,numtype b) {x=a; y=b; }templatenumtype Compare::max( ) {return (x>y)?x:y; }templatenumtype Compare::min( ) {return (x>y)?x:y; }#endif //PROJECT2_COMPARE_H


类库模板 类库模板 (Standard Template Library). 例如:
#include #include using namespace std; int main() {int i = 0; vector v; for (int i = 0; i < 10; ++i) {v.push_back(i); // 把元素一个一个存入到vector中}for (int j = 0; j < v.size(); ++j) {cout << v[j] << " "; // 把每个元素显示出来}return 0; }

输出结果:
0 1 2 3 4 5 6 7 8 9

抽象和实例 C++中模板(Template)详解及其作用介绍
文章图片

到此这篇关于C++中模板(Template)详解及其作用介绍的文章就介绍到这了,更多相关C++模板内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读