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: template
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!