c++中的模板_C ++中的模板

本文详细介绍了C++中的模板,包括功能模板和类模板的使用,如多参数处理、重载及非类型参数。模板允许程序员创建能够处理不同数据类型的通用方法和类,提高代码的可重用性和效率。
摘要由CSDN通过智能技术生成

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++中的模板

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值