博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++中的模板_C ++中的模板
阅读量:2529 次
发布时间:2019-05-11

本文共 8866 字,大约阅读时间需要 29 分钟。

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 
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 
using namespace std; template
T subtract(T x,T y) { T res = x-y; return(res); } int main() { cout<<"Subtraction of numbers of integer type:\n"<
(3,2); cout<<"\nSubtraction of numbers of float type:\n"<
(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:1Subtraction 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
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 
using namespace std; template
void subtract(T1 x,T2 y) { T1 res = x-y; cout<<(res); } int main() { subtract
(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)

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 
using namespace std; template
void area(T1 a) { T1 res = a*a; cout<<"The area of Square:\n"; cout<<(res); } template
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:4The 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 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
object_name;
  • data_type: It refers to the data type associated with the particular class.

    data_type :它是指与特定类关联的数据类型。

Example:

例:

#include 
using namespace std; template
class Compute { public: T subtract(T x,T y) { T res = x-y; return res; } }; int main() { Compute
ob; cout<<"Subtraction function for Integer value as argument\n"; cout<<"Result: "<
<<"\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 argumentResult: 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 Class_name { // Body }

Example:

例:

#include 
using namespace std; template
class Compute { A x; B y; public: Compute(A i,B j) { x = i; y = j; } void show() { cout <
<<","<
<
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 Class_name { //Body };

Example:

例:

#include 
using namespace std; template
class Compute { public: T solve(T x,T y) { T res = x-y + arg; return res; } }; int main() { Compute
ob; cout<<"Result: "<
<<"\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++中的模板

转载地址:http://agozd.baihongyu.com/

你可能感兴趣的文章
[oc学习笔记]多态
查看>>
Tomcat connectionTimeout问题定位处理
查看>>
【PP系列】SAP 取消报工后修改日期
查看>>
ZooKeeper学习第四期---构建ZooKeeper应用(转)
查看>>
JNday4-am
查看>>
UI控件(复习一下)
查看>>
window下自己主动备份数据库成dmp格式的bat写法
查看>>
Memcache存储大数据的问题
查看>>
HDU 5050 Divided Land(进制转换)
查看>>
python进阶学习笔记(三)
查看>>
javascript语法之Date对象与小案例
查看>>
Day45 jquery表格操作、轮播图
查看>>
POJ 2079 Triangle 旋转卡壳求最大三角形
查看>>
【模板】树链剖分
查看>>
计算机博弈研究——六子棋
查看>>
在Visualforce page中用自带的控件实现Ajax回调后台方法(并且可以用js去动态给parameters赋值)...
查看>>
Android驱动开发第七章
查看>>
ISO 9141-2 and ISO 14230-2 INITIALIZATION and DATA TRANSFER
查看>>
特征点检测--基于CNN:TILDE: A Temporally Invariant Learned DEtector
查看>>
CSS3_实现圆角效果box-shadow
查看>>