[C++] How to use templates

The template is the advanced features of C++ divided into:

  • Function template.
  • Class template.

C++ Standard Template Library (STL) 

//General format of function template
/*
template <type parameter table> Return value function name (formal parameter,...){

    //Function body
}
*/

// template keyword
// <> means template parameters (two types)
// 1. type parameters (class / typedef)
// 2. non-type parameters (usually constants)

#include<iostream>
using namespace std;

template <class Type> 
Type max_us(Type x, Type y) {


	return x > y ? x : y;
}
int main() {
	
	int i = max_us(8, 9);

	cout << i << endl;
	return 0;
}

If the types of the two numbers are inconsistent, there will be ambiguity and the compiler cannot recognize them. E.g:

//歧义
	//显示标识模板
	float k = max_us<float>(8.1, 3);

 Need to add display identifier.

A function template is a "framework", it is not a program that can actually compile and generate code, but a template function is a function generated by instantiating the type parameters in a function template. It is essentially the same as a normal function and can generate executable code. .

 Array template use:

//数组模板
template <class Type,int len>

Type max_arr(Type arr[len]) {

	Type ret = arr[0];
	for (int i = 1; i < len; i++)
	{
		ret = (arr[i] > ret ? arr[i] : ret);
	}
	return ret;
}
//数组模板使用
	int max_a = max_arr<int, 5>(a);

	
	cout << max_a << endl;

 Overload template use:

//重载函数模板,实现字符、字符串比较
char* max_us(char* a, char* b) {

	
	if (strcmp(a,b))
	{
		return a;
	}
	else
	{
		return b;
	}
}

 

 

Guess you like

Origin blog.csdn.net/weixin_41865104/article/details/108032413