Simple learning of C++ template

Generic programming: function templates and class templates

Function template:

*template   <typename T>		//typename也可使用class 
void func(T &a){
    
    }*

There are two ways to use templates:
1. Automatic type deduction

func(a)
2、显式指定类型
func<int>(a)

The purpose of the template is to improve the reusability of the code and parameterize the type.
Notes:
·Automatic type derivation, must derive a consistent data type T before it can be used
·The template must determine the data type of T before it can be used

The difference between ordinary functions and templates:
automatic type inference will not have implicit type conversion, and
explicit type will have implicit type conversion

Calling rules for ordinary functions and template functions
· If both function templates and ordinary functions can be implemented, ordinary functions
will be called first
. Function templates can be forced through empty template parameter lists . Function templates can also be overloaded
. If function templates can generate more Good match, call function template first

Limitations of
templates : templates are not omnipotent, some specific data types need to be implemented in specific ways

·利用具体化的模板,可以解决自定义类型的通用化

E.g:

//不同类型排序模板 

#include <iostream>
using namespace std;

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

template<class T>
void mySort(T arr[], int len) 
{
    
    
	for (int i = 0; i < len; i++){
    
    
		int max = i;
		for (int j = i + 1; j < len; j ++){
    
    
			if (arr[max] < arr[j]){
    
    
				max = j;
			}
		}
		if (max != i){
    
    
			mySwap(arr[max], arr[i]);
		}
	}
}

template<class T>
void printArray(T arr[], int len)
{
    
    
	for (int i = 0; i < len; i ++)
	{
    
    
		cout << arr[i] << " ";
	}
	cout <<endl;
}

void test1()
{
    
    
	char charArr[] = "fhdjkhfacb";
	int num = sizeof(charArr);
	mySort(charArr, num);
	printArray(charArr, num);
}

void test2()
{
    
    
	int intArr[] = {
    
    4,455,345,22,4,55,6564,35,3,6757};
	int num = sizeof(intArr) / sizeof(int);
	mySort(intArr, num);
	printArray(intArr, num);
}

int main()
{
    
    
	test1();
	test2();
	system ("pause");
	return 0;
}

*Dark horse programmer c++ course learning exercises

Guess you like

Origin blog.csdn.net/Fighting_gua_biu/article/details/113535334