C + + language function template

Posted by DarkEden on Mon, 27 Dec 2021 19:35:16 +0100

C + + language function template

Generic programming is a programming method in which the algorithm does not specify the type of data to be operated. Genericity means that the algorithm can be applied to multiple data types as long as it is implemented once. The advantage of generic programming method is to reduce the writing of repeated code.

The successful application of generic programming is the standard template library (STL) of C + +. Generic programming is the programming of writing and using a large number of templates.

In C + +, templates are divided into function templates and class templates. When writing a function, consider whether it can be written as a function template, and when writing a class, consider whether it can be written as a class template.

1. C + + function overloading

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

#include <iostream>

using namespace std;

// Swap values of int variables
void Swap(int *a, int *b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}

// Swap the value of the float variable
void Swap(float *a, float *b) {
	float temp = *a;
	*a = *b;
	*b = temp;
}

// Swap values of char variables
void Swap(char *a, char *b) {
	char temp = *a;
	*a = *b;
	*b = temp;
}

// Swap values of bool variables
void Swap(bool *a, bool *b) {
	bool temp = *a;
	*a = *b;
	*b = temp;
}

int main() {
	// Swap values of int variables
	int n1 = 66, n2 = 99;
	Swap(&n1, &n2);
	cout << n1 << ", " << n2 << endl;

	// Swap the value of the float variable
	float f1 = 34.5f, f2 = 78.9f;
	Swap(&f1, &f2);
	cout << f1 << ", " << f2 << endl;

	// Swap values of char variables
	char c1 = 'A', c2 = 'Z';
	Swap(&c1, &c2);
	cout << c1 << ", " << c2 << endl;

	// Swap values of bool variables
	bool b1 = true, b2 = false;
	Swap(&b1, &b2);
	cout << b1 << ", " << b2 << endl;

	return 0;
}

99, 66
78.9, 34.5
Z, A
0, 1
 Please press any key to continue. . .

2. C + + function template pointer

The value of data can be passed through function parameters. When defining a function, the value of the data is unknown. The value can be determined only when the function calls and receives an argument. This is the parameterization of the value.

In C + +, the type of data can also be passed through parameters. The specific data type can not be specified during function definition. When a function call occurs, the compiler can automatically infer the data type according to the passed arguments, which is type parameterization.

Value and type are the two main features of data, which can be parameterized in C + +.

Function template is to establish a general function. The type of data used by it (including return value type, formal parameter type and local variable type) can not be specified specifically, but replaced by a virtual type (actually occupied by an identifier). When a function call occurs, the real type is inversely derived according to the incoming arguments. This general function is called a function template.

In the function template, the values and types of data are parameterized. When a function call occurs, the compiler will deduce the values and types of formal parameters according to the passed arguments. Function templates not only support parameterization of values, but also support parameterization of types.

Once the function template is defined, you can use type parameters for function definitions and function declarations. Where built-in types such as int, float and char are used, type parameters can be used instead.

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

#include <iostream>

using namespace std;

template<typename T>
void Swap(T *a, T *b) {
	T temp = *a;
	*a = *b;
	*b = temp;
}

int main() {
	// Swap values of int variables
	int n1 = 66, n2 = 99;
	Swap(&n1, &n2);
	cout << n1 << ", " << n2 << endl;

	// Swap the value of the float variable
	float f1 = 34.5f, f2 = 78.9f;
	Swap(&f1, &f2);
	cout << f1 << ", " << f2 << endl;

	// Swap values of char variables
	char c1 = 'A', c2 = 'Z';
	Swap(&c1, &c2);
	cout << c1 << ", " << c2 << endl;

	// Swap values of bool variables
	bool b1 = true, b2 = false;
	Swap(&b1, &b2);
	cout << b1 << ", " << b2 << endl;

	return 0;
}
99, 66
78.9, 34.5
Z, A
0, 1
 Please press any key to continue. . .

Template is the keyword that defines the function template. It is followed by angle brackets < >. Angle brackets surround the type parameters (virtual types, or type placeholders). Typename is another keyword used to declare specific type parameters. The type parameter is t. On the whole, template < typename T > is called template header.

The type parameters contained in the template header can be used in various positions of the function definition, including return value, formal parameter list and function body.

The naming rules of Type parameters are the same as those of other identifiers, but it has become a convention to use t, T1, T2, Type, etc.

3. C + + function template - Reference

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

#include <iostream>

using namespace std;

template<typename T>
void Swap(T &a, T &b) {
	T temp = a;
	a = b;
	b = temp;
}

int main() {
	// Swap values of int variables
	int n1 = 66, n2 = 99;
	Swap(n1, n2);
	cout << n1 << ", " << n2 << endl;

	// Swap the value of the float variable
	float f1 = 34.5f, f2 = 78.9f;
	Swap(f1, f2);
	cout << f1 << ", " << f2 << endl;

	// Swap values of char variables
	char c1 = 'A', c2 = 'Z';
	Swap(c1, c2);
	cout << c1 << ", " << c2 << endl;

	// Swap values of bool variables
	bool b1 = true, b2 = false;
	Swap(b1, b2);
	cout << b1 << ", " << b2 << endl;

	return 0;
}

99, 66
78.9, 34.5
Z, A
0, 1
 Please press any key to continue. . .

Syntax for defining template functions:

template <typename Type parameter 1 , typename Type parameter 2 , ...> Return value type function name(parameter list ){
    // Type arguments can be used in the function body
}

There can be multiple type parameters separated by commas. The type parameter list is surrounded by < > and the formal parameter list is surrounded by ().

The typename keyword can also be replaced by the class keyword, and there is no difference between them. In the early days of C + +, the support for templates was not rigorous. Instead of introducing new keywords, class was used to specify type parameters. However, the class keyword was already used in the definition of classes, which seemed unfriendly. Later, C + + introduced a new keyword typename to define type parameters.

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

#include <iostream>

using namespace std;

template<class T>
void Swap(T &a, T &b) {
	T temp = a;
	a = b;
	b = temp;
}

int main() {
	// Swap values of int variables
	int n1 = 66, n2 = 99;
	Swap(n1, n2);
	cout << n1 << ", " << n2 << endl;

	// Swap the value of the float variable
	float f1 = 34.5f, f2 = 78.9f;
	Swap(f1, f2);
	cout << f1 << ", " << f2 << endl;

	// Swap values of char variables
	char c1 = 'A', c2 = 'Z';
	Swap(c1, c2);
	cout << c1 << ", " << c2 << endl;

	// Swap values of bool variables
	bool b1 = true, b2 = false;
	Swap(b1, b2);
	cout << b1 << ", " << b2 << endl;

	return 0;
}

99, 66
78.9, 34.5
Z, A
0, 1
 Please press any key to continue. . .

4. Declare function template

Function templates can be declared in advance, but they need to be declared with a template header, and the template header and function definition (Declaration) are an integral whole. They can wrap lines, but there can be no semicolon in the middle.

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

#include <iostream>

using namespace std;

// Declare function template
template<typename T>
T max(T a, T b, T c);

int main() {
	// Maximum of three integers
	int i1, i2, i3, i_max;
	cin >> i1 >> i2 >> i3;
	i_max = max(i1, i2, i3);
	cout << "i_max = " << i_max << endl;

	// Maximum of three floating point numbers
	double d1, d2, d3, d_max;
	cin >> d1 >> d2 >> d3;
	d_max = max(d1, d2, d3);
	cout << "d_max = " << d_max << endl;

	// Maximum of three long integers
	long g1, g2, g3, g_max;
	cin >> g1 >> g2 >> g3;
	g_max = max(g1, g2, g3);
	cout << "g_max = " << g_max << endl;

	return 0;
}

// Define function templates
// Semicolon is not allowed after the template header
template<typename T>
T max(T a, T b, T c) {
	T max_num = a;
	if (b > max_num) max_num = b;
	if (c > max_num) max_num = c;

	return max_num;
}

1 2 3
i_max = 3
1.5 2.5 3.5
d_max = 3.5
33 22 11
g_max = 33
 Please press any key to continue. . .

References

http://c.biancheng.net/

Topics: C++