Home > Backend Development > C++ > body text

How to create reusable C++ function templates?

王林
Release: 2024-04-15 13:24:01
Original
746 people have browsed it

Function templates can be used to create functions that work on multiple data types by simply specifying the type used, saving time and reducing duplicate code. The specific steps are as follows: Use <class T> to specify the data type. Specify the return type. Name the function. Specify parameter list.

如何创建可重用的 C++ 函数模板?

How to create reusable C function templates

Function templates enable you to create functions that can be used on many types of data. This saves time and reduces the amount of duplicate code.

Syntax

Function templates are declared using the following syntax:

template <class T>
returnType functionName(parameterList) {
   // 函数体
}
Copy after login

where:

  • <class T>Specify the data types to be used for the function's parameters and return value.
  • returnTypeSpecifies the return value type of the function.
  • functionNameSpecifies the name of the function.
  • parameterListSpecifies the parameter list of the function.

Practical case

Let us create a function template that finds the sum of array elements:

template <class T>
T sumArray(T arr[], int size) {
    T sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}
Copy after login

This function template can be used for any data Array of type T.

Using

To use a function template, simply specify the type you want to use. For example, to find the sum of an array of integers, you would do this:

int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = sumArray<int>(arr, size);
Copy after login

Similarly, to find the sum of an array of floats, you would do this:

float arr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
int size = sizeof(arr) / sizeof(arr[0]);
float sum = sumArray<float>(arr, size);
Copy after login

Advantages

Advantages of using function templates include:

  • Code reuse: You can create functions that can be used on multiple types of data.
  • Reduce code size: You don’t have to write a separate function for each data type.
  • Improve readability: Function templates help make your code easier to read and understand.

The above is the detailed content of How to create reusable C++ function templates?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!