跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

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;}写成函数模板的形式: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_H

template // 虚拟类型名为numtype class 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_H

template // 虚拟类型名为numtype class 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++模板内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:C++模板template用法小结(推荐) C++中的模板template小结C++ Template 基础篇(一):函数模板详解C++设计模式之模板方法模式(TemplateMethod)

C++的template模板中class与typename关键字的区别分析C++设计模式编程中Template Method模板方法模式的运用C++模板Template详解及其作用介绍

相关文章