Introduction to the template function in C++

. Preface
The templates in C++ are divided into function templates and class templates.
In C++, templates allow us to extract the logic of processing problems from different data types to form containers and algorithms.
When we need to access and process certain data, we can select the appropriate template to specify the data type we need in the program. At this time, the compiler will generate suitable containers and algorithms for this type of data for us. function.

.Function template
1.
The problem of multiple overloaded function bodies with the same or almost the same situation is not only redundancy, but also when you plan to modify the algorithm, if you do not make synchronous modifications in each function body , It will also cause inconsistent algorithms to deal with the same types of problems in the same system, leading to inconsistencies.

2. Example
Question: Do you need to write two overloaded functions to calculate the absolute value of the integer type and the floating-point number type?

int abs(int x)
{
    
    
	return x < 0 ? -x : x;
}
double abs(double x)
{
    
    
	return x < 0 ? -x : x;
}
//两函数体相同,仅参数类型不同,产生冗余

Solution: Function template
Function:
.Create a function with general functions;
.Support a variety of different formal parameters;
.Simplify the function body design of overloaded functions.

template<typename  T>
T abs(T x)
{
    
    
	return x < 0 ? -x : x;
}
//编译器根据实参类型,推导出类型(简单理解为在调用时用对应类型的标识符代替)

3. Definition
Function template is not a real function, and the compiler cannot generate executable code for it. After the function template is defined, it is just a description of the function framework. When it is executed, its function will be determined according to the actual parameters passed.

4. Format
Function template definition syntax
. Syntax form:
template<template parameter table>
function definition
. Template parameter table content
. Type parameters:. class(或typename)标识符
Constant parameters: 类型说明符 表示符
template parameters:template<参数表> class 标识符

.Class template
1. The role of class template. The
use of class template allows users to declare a mode for the class, so that some data members in the class, the parameters of some member functions, and the return value of some member functions can take any type ( Including basic basic types and user-defined types)

2. Format
Class template:

template<模板参数表>
class 类名
{
    
    
类成员声明
}

If you need to define its function outside of the class template, it must take the following form:

template<模板参数表>
类型名 类名<模板参数标识符列表>::函数名(参数名)

Example:

#include <iostream>
using namespace std;
struct Student
{
    
    
	int id;    //学号
	float gpa; //平均分
};

template<class T>
class Store//类模板:实现对任意数据进行存取
{
    
    
public:
	Store();
	T& getElem();              //提取数据函数
	void putElem(const T& x);  //存入数据函数
private:
	T item;                    //item用于存放任意类型的数据
	bool haveValue;            //haveValue标记item是否已被存入内容
};

//函数实现
//定义Store()
template <class T>
Store<T>::Store():haveValue(false){
    
    }
//定义getElem()
template <class T>
T& Store<T>::getElem()
{
    
    
	//如试图提取未初始化的数据,则终止程序
	if(!haveValue)
	{
    
    
		cout << "No item present!" << endl;
		exit(1);//使程序完全退出,返回操作系统
	}
	return item;     //返回item中存放的数据
}
template <class T>
void Store<T>::putElem(const T& x)
{
    
    
	//将haveValue置为true,表示item中已存入数值
	haveValue = true;
	item = x;        //将x值存入item
}


int main()
{
    
    
	Store<int> s1, s2;//此时整型int代替T,可简单理解为有个函数Store<数据类型>,会把之前暂未定义的数据类型给替代为<>中的数据类型
	s1.putElem(3);
	s2.putElem(-7);
	cout << s1.getElem() << " " << s2.getElem() << endl;

	Student g = {
    
     1000,23 };
	Store<Student> s3;
	s3.putElem(g);
	cout << "The student id is" << s3.getElem().id << endl;//s3.getElem返回了Student类型

	Store<double> d;
	cout << "Retrieving object D...";
	cout << d.getElem() << endl;
	//d未初始化,执行函数D.getElement()时导致程序终止
	
	return 0;
}

The result is:

3 -7
The student id is1000
Retrieving object D...No item present!

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/114242398