C++ templates (function templates, class templates)


introduction

Thought determines action, action forms habit, habit forms quality, and quality determines destiny. —— Tao Xingzhi

This chapter is about the initial templates of C++. The full text is not counted as the pitiful number of code words, but templates are a treasure that we must learn in C++. His appearance is a leap forward achievement of C++! The following will mainly learn grammar in the form of code.

Not much to say, fasten your seat belt, let's start the car (recommended to watch on computer) .


Attachment: red, the part is the key part; the blue color is the part that needs to be memorized (not rote memorization, knock more); black bold or other colors are the secondary key points; black is the description need


mind Mapping:

If you want XMind mind map, you can private message


Table of contents

1. Generic programming

2. Function template

2.1 The principle of implementing templates

2.2 Instantiation of function templates

3. Class Templates


1. Generic programming

Knowledge points:

Generic programming: Writing generic code that has nothing to do with types is a means of code reuse . Templates are a bit of an abstraction at the base of generic programming .

Although they can use function overloading to implement some highly repetitive codes, there is a downside after all. The overloaded functions are only of different types, and the code reuse rate is relatively low. Users need to add corresponding functions by themselves , and the maintainability of the code is relatively low . One error may cause errors in all overloads.
Specifically, the following code shows it in detail:
the following is the swap exchange function. At this time, different exchange functions are required for different types:

void swap(int& x, int& y)
{
    int tmp = x;
    x = y;
    y = tmp;
}

void swap(char& x, char& y)
{
    char tmp = x;
    x = y;
    y = tmp;
}

void swap(float& x, float& y)
{
    float tmp = x;
    x = y;
    y = tmp;
}

// ......

For c++ , in order to solve this problem, a new syntax is proposed: template (the template is like a mold, the shapes of the things we create are the same, but the materials we put in are different, and the things that come out are different. In In the above exchange functions, the exchange method is the same, but their types are different, that is, the so-called change of soup is still the same, so templates can be used to quickly realize the creation of similar functions ).


2. Function template

Knowledge points:

Function template concept: A function template represents a family of functions. The function template has nothing to do with the type, is parameterized when used, and generates a specific type version of the function according to the actual parameter type.
Template syntax:

template<typename T1, typename T2 ...> 、 template<class T, ....>  

return value type function name (argument list)

{}

  • Among them, class and typename have the same effect and we can use it

  • Templates need to appear right next to the function that requires the template. The scope of use of template parameters is in the domain of the function/class below it.

 Use exercises ( see notes ):

//template<class Ty>和下面的是效果一样的,并且内部的Ty是和变量名一样可以自行diy的
template<typename T>
void Swap(T& x, T& y) {
	T tmp = x;
	x = y;
	y = tmp;
}


// 我们可以定义多个模板参数,来分开识别使用,防止出现两个参数的类型不同的情况
template<class T1,typename T2>
void Func(T1& x, T2& y)//此处定义了两个模板参数,就能对应对当两个类型不同的情况
{
	cout << x << ' ' << y << endl;
}

int main()
{
	int a = 0 , b = 1;
	double c = 1.1, d = 2.2;
	Swap(a, b);
	Swap(c, d);


	int e = 10;
	double f = 10.4;
	Func(e, f);

	return 0;
}


detail:

2.1 The principle of implementing templates

The realization principle of the template is very similar to that in reality. Through a mold, a similar process is repeated many times , and the mold is just like the function under the template in the above code. In this process , the mold will be created. Multiple invisible overloaded functions actually create multiple functions and call these functions in essence, but the implementation process is replaced by the compiler ( template instantiation ).

Note: Although they use the same template, the functions they call are different!

Attachment: In fact, the swap function has been written for us in the c++ library, so from later on we don’t need to implement the swap function ourselves, just use it directly, swap(variable, variable);


2.2 Instantiation of function templates

  • When a function template is used with parameters of different types, it is called instantiation of the function template.
  • Template parameter instantiation is divided into: implicit instantiation and explicit instantiation
  1. Implicit instantiation : to directly identify the type for the parameter, and then create a function for the template parameter, just like the above exercise.
  2. Display instantiation : determine the type of the template parameter directly to the function before calling it

Example exercise:

Show instantiated writing:

Add square brackets between functions and parameters, and add types inside, such as: Func<int>(a,b).

details as follows:

template<typename T>
T* Alloc(int n)
{
	return new T[n];
}

int main()
{
	int* ptr = Alloc<int>(10);//此时的<int>就是一个显示的实例化,直接给这个函数的模板参数定义了类型int
	return 0;
}

3. Class Templates

Knowledge points:

  • The definition format of class templates: the usage methods and functions of class templates and function templates are almost the same, but the usage is slightly different (the details will be shown through the code)
  • For function templates, its scope is the local function area next to it , while for class templates, it acts on the entire class area next to it.

detail:

If a class template is added, the type of its class will be changed: 

Type: className <all template parameters> 

The class name is still the same  

Practice using (understand again, note notes) :

template<typename T>
class Stack
{
public:
	Stack(int capacity = 4)
	{
		_arr = new T[capacity];
		int _size = 0;
		int _capacity = capacity;
	}

	void Push(const T& x);


	~Stack()
	{
		delete _arr;
		_size = 0;
		_capacity = 0;
	}

private:
	T* _arr;
	int _size;
	int _capacity;
};

template<typename T>
void Stack<T>::Push(const T& x)//此时我们定义全局函数时,需要我们指定类域才能使用其内部的成员
//而对于函数模板来说,此时的类型也该变成 Stack<模板参数>
{
	//CheckCapacity()
	_arr[_size] = x;
	_size++;
}

int main()
{
	Stack<int> st1;//显示实例化,此处必须加上这个显示...
	Stack<double> st2;//double

	//这样写我们就不用像cyy那样需要去改变 TypeDate 了
	//并且,可以同时使用多种类型的栈
    //C语言不能同时拥有,因为C语言的TypeDate只能在一处使用,就导致定死后不能用于
	//另外一处新的类型的对象中,而模板就能突破这个界限,创建多个类型不同功能一样的函数
	return 0;
}

This chapter is over. To predict what will happen next, let's wait for the next chapter to break it down.

If you have any questions, welcome to discuss!

If you think this article is helpful to you, please like it!

Continuously update a large number of C++ detailed content, pay attention early and don't get lost.

Guess you like

Origin blog.csdn.net/ZYK069/article/details/130865195