Home  >  Article  >  Backend Development  >  How does generic programming in C++ achieve code reuse through class templates?

How does generic programming in C++ achieve code reuse through class templates?

WBOY
WBOYOriginal
2024-06-01 22:12:00716browse

Generic programming allows code that uses different types of data to be implemented by creating class templates, where T is the type parameter. The syntax for creating a class template is: template75a837cf562f69348eb0e119bf9e56d8 class MyClass {/class definition/}. To use a class template, instantiate it with a concrete type: MyClassbd43222e33876353aff11e13a7dc75f6 myIntClass. In practice, you can use the class template ArrayMultiplier to multiply the elements in the array by a specific value without specifying the type of the array element: ArrayMultiplier8742468051c85b06f0a0af9e3e506b5c myMultiplier; myMultiplier.multiply(arr, arrSize, multiplier).

C++ 中的泛型编程如何通过类模板实现代码复用?

Using Class Templates to Implement Generic Programming in C

Generic programming is a technique that allows you to write usable codes for different types of data. This can be achieved by creating a class template that defines a class with type parameters.

Creating a class template

To create a class template you need to use the following syntax:

template <typename T>
class MyClass {
    // 类定义
};

Here, T is Type parameters, which will be replaced with concrete types.

Using Class Templates

To use a class template, instantiate it using a concrete type. For example:

MyClass<int> myIntClass;

This will create an instance of MyClass with T replaced by int.

Practical Case

Let us consider a function that multiplies the elements in an array by a certain value:

void multiplyArray(int* arr, int size, int factor) {
    for (int i = 0; i < size; i++) {
        arr[i] *= factor;
    }
}

This function can only be used with integers array. To make it universal for any type of data, we can use a class template:

template <typename T>
class ArrayMultiplier {
public:
    void multiply(T* arr, int size, T factor) {
        for (int i = 0; i < size; i++) {
            arr[i] *= factor;
        }
    }
};

To use this class, we instantiate ArrayMultiplier and call the multiply method:

ArrayMultiplier<int> intMultiplier;
int arr[] = {1, 2, 3};
intMultiplier.multiply(arr, 3, 10);

Now this code can be used for any type of array without any modification.

The above is the detailed content of How does generic programming in C++ achieve code reuse through class templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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