Templates in C++ - C++ 中的模板

Templates in C++ - C++ 中的模板

Templates are used to prevent us from writing the same function or class separately for different data types. We normally use templates in large programs where we have to define the same function or class for different data types.
模板用于防止我们为不同的数据类型分别编写相同的函数或类。通常,我们在大型程序中使用模板,其中我们必须为不同的数据类型定义相同的函数或类。

//============================================================================
// Name        : std::template
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

int sum(int x, int y)
{
	return x + y;
}

float sum(float x, float y)
{
	return x + y;
}

double sum(double x, double y)
{
	return x + y;
}

int main()
{
	cout << "sum_int : " << sum(3, 5) << endl;
	cout << "sum_float : " << sum(3.0, 5.2) << endl;
	cout << "sum_double : " << sum(3.24234, 5.24144) << endl;
	return 0;
}

Output

sum_int : 8
sum_float : 8.2
sum_double : 8.48378

In this example, we defined a separate function to calculate the sum of three sets of numbers, each with a different data type.
在此示例中,我们定义了一个单独的函数来计算三组数字之和,每组数字具有不同的数据类型。

hectic [ˈhektɪk]:adj. 紧张忙碌的,肺病的,脸上发红的,狂热的 n. 脸红,患肺结核

This is where we need templates. There are two types of templates in C++.
这是我们需要模板的地方。C++ 中有两种类型的模板。

  • Function Templates
  • Class Templates

1. Function Templates

Function Templates prevent us from defining separate functions performing the same task for different data types. Let’s look at the syntax of a function template for the sum function in the above example.
函数模板阻止我们定义针对不同数据类型执行相同任务的独立函数。让我们看一下上面示例中 sum 函数的函数模板的语法。

T sum(T x, T y)
{
    return x + y;
}

Compare this function template with the function in the previous example. You will notice that this function template is the same as the function in the example, except for the difference that here we have declared the parameter of type T instead of int, float or double.
将此函数模板与上一个示例中的函数进行比较。您会注意到该函数模板与示例中的函数相同,不同之处在于在这里我们声明了类型为 T 的参数,而不是 int, float or double

We need to tell the compiler that this is a function template because it will not identify T ( since T is not a keyword ). For this, we need to include the following code before including T as shown below.
我们需要告诉编译器这是一个函数模板,因为它无法识别 T(因为 T 不是关键字)。为此,我们需要在包含 T 之前包含以下代码,如下所示。

template <typename T>        // declaring function template with template parameter

This will tell the compiler that T is a type of template parameter.
这将告诉编译器 T 是模板参数的一种。

Let’s see the above example of printing the sum of different data types using function template.
让我们看一下上面的示例,该示例使用功能模板打印不同数据类型的总和。

//============================================================================
// Name        : std::template
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

template<typename T>
T sum(T x, T y)
{
	return x + y;
}

int main()
{
	cout << "sum_int : " << sum(3, 5) << endl;
	cout << "sum_float : " << sum(3.0, 5.2) << endl;
	cout << "sum_double : " << sum(3.24234, 5.24144) << endl;

	return 0;
}

Output

sum_int : 8
sum_float : 8.2
sum_double : 8.48378

Here we declared a function template instead of writing three different functions for each data type.
在这里,我们声明了一个函数模板,而不是为每种数据类型编写三个不同的函数。

T sum(T x, T y) - This is the definition of the function template which is the same as that of function. This tells us that both the parameters are of type T and the return value is also of type T.
这是函数模板的定义,与函数相同。这告诉我们两个参数都是 T 型,返回值也是 T 型。

sum(3, 5) - Since both the arguments (3 and 5) are of type int, hence T will be of type int. Thus, in this case, the function template becomes the function in the first example.
由于参数 (3 和 5) 均为 int 类型,因此 T 将为 int 类型。因此,在这种情况下,函数模板成为第一示例中的功能。

Similarly, in the case of sum(3.0, 5.2), T becomes of type float and the template becomes same as the second function in the first example. Same is in the third case.
类似地,在 sum(3.0, 5.2) 的情况下,T 变为 float 类型,并且模板与第一个示例中的第二个函数相同。第三种情况类似。

We can also write class keyword in place of typename keyword while declaring the template parameter.
我们也可以在声明 template 参数的同时,用 class 关键字代替 typename 关键字。

We can also write the following code by replacing the typename keyword by class keyword.
我们也可以通过将 typename 关键字替换为 class 关键字来编写以下代码。

template < class T >        // declaring template parameter

In the above example, both the parameters of the function template were of the same type. Hence we declared T for both.
在上面的示例中,函数模板的两个参数均为同一类型。因此,我们对两者都声明了 T

Suppose we are multiplying an integer with a floating number and we have to define a function for that. Then its one parameter will be of type int and another of type float. In that case, we will define the function template with a different type for each parameter as shown below.
假设我们将一个整数与一个浮点数相乘,并且必须为此定义一个函数。然后,它的一个参数将是 int 类型,另一个参数将是 float 类型。在这种情况下,我们将为每个参数定义具有不同类型的函数模板,如下所示。

template         // declaring template parameters
T2 product(T1 x, T2 y)
{
    return x * y;
}

Here we declared the function template with two types of template parameters T1 and T2, where T1 is the datatype of its first parameter which is an integer value and T2 is of the second parameter which is a floating value. Since the product of an int and a float is a float, hence its return type is also T2.
在这里,我们用两种类型的模板参数 T1 and T2 声明了函数模板,其中 T1 是其第一个参数的数据类型,它是一个整数值,而 T2 是第二个参数的数据类型,它是一个浮点值。由于 intfloat 的乘积是 float,因此其返回类型也是 T2

//============================================================================
// Name        : std::template
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

template<typename T1, typename T2>
T2 product(T1 x, T2 y)
{
	return (T2) (x * y);
}

int main()
{
	cout << product(3, 4.7) << endl;
	cout << product(4, 5.6) << endl;

	return 0;
}

Output

14.1
22.4

2. Class Templates

We can create class templates just like function templates.
我们可以像函数模板一样创建类模板。

Consider two students in a class and we want to calculate the total marks of each of them in two subjects. Suppose the marks of the first student in both the subjects are integer values and that of the second student floating values.
考虑一个班上有两个学生,我们想计算每个学生两个科目的总成绩。假设两个科目中第一位学生的分数均为整数,第二位学生的分数为浮点值。

//============================================================================
// Name        : std::template
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

template<class T>
class Student
{
	T marks1;
	T marks2;

public:
	Student(T m1, T m2)
	{
		marks1 = m1;
		marks2 = m2;
	}

	T totalMarks()
	{
		return marks1 + marks2;
	}
};

int main()
{
	Student<int> s1(45, 50);
	Student<float> s2(47.5, 56.4);

	cout << "Total marks of student1 : " << s1.totalMarks() << endl;
	cout << "Total marks of student2 : " << s2.totalMarks() << endl;

	return 0;
}

Output

Total marks of student1 : 95
Total marks of student2 : 103.9

Here, s1 and s2 are the two objects of class Student and marks1 and marks2 are the marks of the students in first and second subject respectively.
这里,s1 and s2class Student 的两个对象,而 marks1 和 marks2 分别是第一和第二科目的学生的分数。

Student s1 (45, 50); - This statement created an object s1 of class Student and assigned 45 and 50 as marks1 and marks2 respectively. Since both are integer values, therefore T is of type int. Also, the return value of the member function totalMarks() is also of type int because the sum of two integers is an integer.
此语句创建了 Student 类的对象 s1,并分别将 45 和 50 分配为 mark1 和 mark2。由于两者都是整数值,因此 Tint 类型。同样,成员函数 totalMarks() 的返回值也为 int 类型,因为两个整数的和为整数。

Student s2 (47.5, 56.4); - This created the second object s2 having the values of both marks1 and marks2 float. Hence, T is a float in this case.
这创建了第二个对象 s2,其第二个对象的 marks1 和 marks2 的值为浮点数。因此,在这种情况下,T 是浮点数。

inheritance [ɪnˈherɪtəns]:n. 继承,遗传,遗产
class:类
derived class:继承类,派生类
subclass:子类
base class:基类
superclass:超类,父类
passion [ˈpæʃn]:n. 激情,热情,酷爱,盛怒

References

https://www.codesdope.com/cpp-multiple-inheritance/

发布了454 篇原创文章 · 获赞 1734 · 访问量 103万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104459411
今日推荐