Function templates allow code to be written in a type-independent manner, providing compile-time polymorphism. The syntax is template<typename T>, where T is the template parameter. Function templates can be used for a variety of tasks, such as swapping elements or finding the maximum value in an array. Templates must be declared before use, and it is best to avoid using pointers in templates.
Syntax and usage of C function template
Introduction
Function template is A powerful tool in C that allows us to write reusable code regardless of data type. Function templates provide compile-time polymorphism, which is different from run-time polymorphism (for example, using virtual methods).
Syntax
Function templates are defined using < >
subscripts and template parameters. The syntax is as follows:
template<typename T> returnType functionName(T param1, T param2, ...) { ... }
Where:
template<typename T>
specifies that the template parameter is of type T
. returnType
is the return value type of the function. functionName
is the function name. param1
, param2
, ... are parameters of the function, type is T
. Example
We take a simple function template that exchanges two elements as an example:
template<typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; }
This template can be used for any Data types, including int, float, string, etc.
Practical case
Find the maximum value
We can use the function template to write a function to find the maximum value in the array Function:
template<typename T> T findMax(T* arr, int size) { T max = arr[0]; for (int i = 1; i < size; i++) { if (arr[i] > max) { max = arr[i]; } } return max; }
This function template can be used to find the maximum value in any type of array such as int, float, string, etc.
Notes
template <typename T where is_arithmetic<T>>
). The above is the detailed content of Syntax and usage of C++ function templates. For more information, please follow other related articles on the PHP Chinese website!