c++中的模板

Templates in C++ are an abstract version of Generic Programming wherein the code is written in an independent manner i.e. completely independent of the other blocks of code within the same program.

C ++中的模板是通用编程的抽象版本,其中代码以独立的方式编写,即完全独立于同一程序中的其他代码块。

With templates, you can create generic methods and classes, where data types are passed along with the data as arguments to reduce code redundancy.

使用模板,您可以创建通用方法和类,其中数据类型与数据一起作为参数传递,以减少代码冗余。

We can create a single method and/or a class that works with different data types without having to redefine the structure of the function or define a new function.

我们可以创建一个用于不同数据类型单一方法和/或类 ,而无需重新定义函数的结构或定义新的函数。

Thus, templates enable the programmer to define a method or class without having a prior idea about the data type of the variables it would be dealing with ahead.

因此,模板使程序员可以定义方法或类,而无需事先了解将要处理的变量的数据类型。



在C ++中使用模板 (Working of Templates in C++)

Templates in C++ resemble the working logic of macros in system programming.

用C ++模板类似系统编程的的工作逻辑。

  • At the time of generating the code to be compiled, the code contains only the methods/classes.在生成要编译的代码时,该代码仅包含方法/类。
  • While compiling the code, the compiler replaces the functions/classes with the desired or required data type as per the function calls.在编译代码时,编译器会根据函数调用以所需或所需的数据类型替换函数/类。

Thus, in a template, a single function/class handles data with multiple data types within it.

因此, 在模板中,单个函数/类可处理其中具有多种数据类型的数据



模板入门 (Getting started with Templates)

Templates in C++ can be used to create and define the following:

C ++中的模板可用于创建和定义以下内容:

  • Classes: Creates a template class containing any template type or non-template type variable as an argument.Classes :创建一个包含任何模板类型或非模板类型变量作为参数的模板类。
  • Functions/Methods: Creates a Template function containing any template type or non-template type variable as an argument.Functions/Methods :创建一个包含任何模板类型或非模板类型变量作为参数的模板函数。


1. C ++中的功能模板 (1. Function Templates in C++)

Function Templates work and handle different data types within a function in a single flow of the program.

功能模板在程序的单个流程中工作并处理功能内的不同数据类型。

Syntax:

句法:


template <class type> type fun_name(argument_list)
{  // body
}
  • type is just a placeholder/template argument and it represents the data type of the function/class.type只是一个占位符/模板参数 ,它表示函数/类的数据类型。
  • class is basically a keyword to describe the generic function/class type in the template declaration. The keyword class can also be replaced by typename.class基本上是描述模板声明中泛型函数/类类型的关键字 。 关键字class也可以用typename代替。

Example:

例:


#include <iostream>
using namespace std;
template<class T> T subtract(T x,T y)
{  T res = x-y;  return(res);  }
int main()
{  cout<<"Subtraction of numbers of integer type:\n"<<subtract<int>(3,2);  cout<<"\nSubtraction of numbers of float type:\n"<<subtract<float>(5.3,3.2); return 0;
}

In the above snippet of code, we have created a template function called subtract with two variables – x, y as arguments to it.

在上面的代码片段中,我们创建了一个名为减法的模板函数,带有两个变量– x,y作为其参数。

During the compilation of the program, it assigns the particular data type to the function. i.e. while running the code at dynamic type it checks for the type of the passed arguments to the calling function and then takes the execution ahead.

在程序编译期间,它将特定的数据类型分配给函数。 即在以动态类型运行代码时,它会检查传递给调用函数的参数的类型,然后提前执行。

Output:

输出:


Subtraction of numbers of integer type:
1
Subtraction of numbers of float type:
2.1


功能模板的多个参数 (Multiple arguments with Function Templates)

Function Templates in C++ can have multiple generic types of arguments in it.

C ++中的函数模板中可以包含多种通用类型的参数

Syntax:

句法:


template<class T1, class T2,.....>
type fun_name (parameters of generic type T1, T2....)
{  // body of function.
}

Here, class T1 and T2 describe the different types of generic functions.

在这里,类T1T2描述了通用函数的不同类型。

Example:

例:


#include <iostream>
using namespace std;
template<class T1, class T2>
void subtract(T1 x,T2 y)
{  T1 res = x-y;  cout<<(res);  }
int main()
{  subtract<double, int>(3.5,2);  return 0;
}

In the above snippet of code, we have passed a float type value as the data type for T1 and int type value for the data type for T2.

在上面的代码片段中,我们传递了一个float类型值作为T1的数据类型,并将int类型值作为T2的数据类型。

Output:

输出:


1.5


功能模板的重载 (Overloading of a Function Template)

Overloading of Function Templates in C++ indicates that the overloaded function would contain different types of arguments.

C ++ 中函数模板的重载表明重载的函数将包含不同类型的参数。

Let’s go through the below example in order to understand Function Overloading in Templates.

让我们看一下下面的示例,以了解模板中的函数重载。


#include <iostream>
using namespace std;
template<class T1>
void area(T1 a)
{  T1 res = a*a;cout<<"The area of Square:\n";cout<<(res);  }  template<class T1, class T2>
void area(T1 l,T2 b)
{  T1 res = l*b;  cout<<"\nThe area of Rectangle:\n";cout<<(res);  } int main()
{  area(2);area(3.5,1);return 0;
}

In the above snippet of code, we have overloaded theareafunction wherein, we have calculated the area of a Square and a Rectangle by passing different types of arguments to the corresponding function.

在上面的代码片段中,我们重载了area函数,其中,我们通过将不同类型的参数传递给相应的函数来计算Square和Rectangle的面积。

Output:

输出:


The area of Square:
4
The area of Rectangle:
3.5


2. C ++中的类模板 (2. Class Templates in C++)

Class Templates help define different types of classes by passing the data type associated with it.

类模板通过传递与之关联的数据类型来帮助定义不同类型的类。

It can be termed as a generic class because the data type of the class and its operations is decided at the time of compilation by passing a particular type associated with the functions of the class.

之所以可以将其称为generic class是因为在编译时通过传递与该类的功能相关联的特定类型来确定generic class的数据类型及其操作。

Syntax:

句法:


template<class type>
class Class_name
{  //body
}
  • type is just a placeholder/template argument and it represents the data type of the class.type只是一个占位符/模板参数 ,它表示类的数据类型。

In order to create the instance of the class, we need to follow the following statement:

为了创建该类的实例,我们需要遵循以下语句:


Class_name<data_type> object_name;
  • data_type: It refers to the data type associated with the particular class.data_type :它是指与特定类关联的数据类型。

Example:

例:


#include <iostream>
using namespace std;
template<class T>
class Compute
{ public:T subtract(T x,T y)  {  T res = x-y;  return res;  }
};  int main()
{  Compute<int> ob;cout<<"Subtraction function for Integer value as argument\n";cout<<"Result: "<<ob.subtract(10,5)<<"\n" ;return 0;
}

In the above code snippet, we use the template T to pass the data

在上面的代码片段中,我们使用模板T传递数据

Output:

输出:


Subtraction function for Integer value as argument
Result: 5


类模板的多个参数 (Multiple arguments with Class Templates )

Class Templates can have multiple arguments i.e. more than one generic type in a class.

类模板可以具有多个参数,即一个类中可以有多个通用类型。

Syntax:

句法:


template<class T1, class T2, class T3, ......, class Tn>
class Class_name
{  // Body
}

Example:

例:


#include <iostream>
using namespace std;
template<class A, class B>
class Compute
{  A x;  B y;  public:  Compute(A i,B j)  {  x = i;  y = j;  }  void show()  {  cout <<x<<","<<y<<endl;  }  };  int main()  {  Compute<float,int> ob(5.5,2);  ob.show();  return 0;  }  

In the above snippet of code, we have passed two generic types A and B respectively.

在上面的代码片段中,我们分别传递了两个通用类型AB。

While creating an instance of the class, we have passed float and int as the data type for generic types A and B and have used a class Constructor to initialize the data member’s values and have displayed the same.

在创建类的实例时,我们将floatint作为通用类型A和B的数据类型传递,并使用类Constructor 初始化数据成员的值并显示出它们。

Output:

输出:


5.5,2


模板中的非类型参数 (Non-type arguments in Templates)

Class templates can contain multiple parameters too. These parameters can be of the generic type or non-type arguments such as constants, method names, string, etc.

类模板也可以包含多个参数。 这些参数可以是通用类型,也可以是非类型参数,例如常量,方法名称,字符串等。

Syntax:

句法:


template<class T, data_type var-name>
class Class_name
{  //Body
};

Example:

例:


#include <iostream>
using namespace std;
template<class T, int arg>
class Compute
{  public:T solve(T x,T y)  {  T res = x-y + arg;return res;     }
};  int main()
{  Compute<int, 10> ob;cout<<"Result: "<<ob.solve(10,5)<<"\n" ;return 0;
}  

Here, we have passed arg of type int as an argument to the Class Template and have passed its value during the function call in the main function.

在这里,我们将int类型的arg作为参数传递给类模板,并在主函数的函数调用期间传递了它的值。



结论 (Conclusion)

In this article, we have unveiled the working of Templates and have understood how function and class templates lead to the re-usability of the code and better efficiency too.

在本文中,我们揭露了模板的工作原理,并且了解了函数和类模板如何导致代码的可重用性以及更高的效率。



参考资料 (References)

C++ Template Documentation

C ++模板文档

翻译自: https://www.journaldev.com/36453/templates-in-c-plus-plus

c++中的模板

c++中的模板_C ++中的模板相关推荐

  1. c#中如何删除数组中的元素_C中的数组

    c#中如何删除数组中的元素 为什么我们需要数组? (Why do we need Arrays?) Consider the problem of storing 10 integers. The n ...

  2. c语言中优先级队列_C ++中的优先级队列

    c语言中优先级队列 A Priority Queue is a variant of a Queue such that it's elements are ordered based on thei ...

  3. c语言面向对象编程中的类_C ++中的面向对象编程

    c语言面向对象编程中的类 Object oriented programming, OOP for short, aims to implement real world entities like ...

  4. python中双冒号_c++中冒号(:)和双冒号(::)的用法和c/c++ 位域结构体

    1.冒号(:)用法 (1)表示结构体内 位域的定义(即该变量占几个bit空间) typedef struct _XXX{ unsigned char a:4; unsigned char c; }XX ...

  5. c++中的队列_C ++中的队列

    c++中的队列 介绍 (Introduction) We worked on the working as well as the implementation of a Stack in C++ i ...

  6. c++中的向量_C ++中的向量

    c++中的向量 A Vectors in C++ is an array-like container that can change dynamically in size. Being a par ...

  7. for循环在c++中的用法_C ++中的循环

    for循环在c++中的用法 Loops come into picture when we need to execute a particular action in a repeated mann ...

  8. C语言面向对象编程的类是指,c语言面向对象编程中的类_C ++中的面向对象编程...

    c语言面向对象编程中的类 Object Oriented programming is a programming style that is associated with the concept ...

  9. c++ 的 stl模板库_C ++中的标准模板库(STL)

    c++ 的 stl模板库 Standard Template Library (STL) is a collection of standard C++ template classes. It co ...

最新文章

  1. css揭秘之linear-gradient
  2. 001-supervisor
  3. 【Flutter】Dart 面向对象 ( mixins 特性 )
  4. python字符串、元组常用操作
  5. Python基础教程:列表推导式对比For循环执行效率
  6. 西门子200恒压供水梯形图_求西门子plc200恒压供水编程实例(梯形图)急急急......望高手指点!...
  7. 实验2 递归和分治法(二分查找)
  8. POJ1006-Biorhythms【中国剩余定理】
  9. 【渝粤题库】陕西师范大学151204 中级财务会计作业(笔试题型)
  10. mysql修改字段结构_MySQL修改表结构及其添加删除修改字段功能
  11. C语言深度解剖:关键字
  12. php.ini – 配置文件详解
  13. 移动测试基础 android 中 dumpsys 命令使用
  14. 兄弟j220怎么清零_兄弟j220怎么清零_兄弟Brother全系列打印机清零大全
  15. linux vim替换指定字符串
  16. 班级校园网页设计作业 静态HTML我的班级网页 DW班级网站模板下载 大学生简单班级网页作品代码 我的大学网页制作 学生班级网页设计作业
  17. 用 Python 分析《长安十二时辰》
  18. 推荐阅读蔡颖先生新作-APS走向实践
  19. Ubuntu中使用RoboMongo实现MongoDB的可视化
  20. 天津最新建筑施工八大员之(安全员)考试真题及答案解析

热门文章

  1. Java排序:冒泡排序
  2. 1588: [HNOI2002]营业额统计 - BZOJ
  3. [转载] python中count()、values_counts()、size()函数
  4. [转载] [转载] python set集合如何有序输出_python set集合的用法
  5. delphi 7 mdi子窗体。。。无法更改以命令对象为源的记录集对象的 ActiveConnection 属性。...
  6. R 学习笔记《五》 R语言初学者指南--第二章总结
  7. HTML Meta标签详解
  8. CentOS下安装实时检测网络带宽的小工具bmon
  9. Android自定义样式
  10. CV学习笔记-特征提取