Home  >  Article  >  Backend Development  >  How to implement generic classes in C++?

How to implement generic classes in C++?

王林
王林Original
2024-06-06 13:13:57402browse

Implementing generic classes in C++: using templates, specifying placeholders for types. Create an instance of a generic class, specifying type parameters. Generic classes allow the same code to be used for different data types. Practical application: Use the generic StudentArray class to store and process different types of data, such as student names.

How to implement generic classes in C++?

How to implement generic classes in C++

Generic classes allow you to create code that can use different type of data. Here's how to implement a generic class in C++:

#include 

template 
class GenericClass {
public:
    GenericClass(T value) : val(value) {}
    void print() {
        std::cout << "Value: " << val << std::endl;
    }
private:
    T val;
};

In this example, GenericClass is a generic class and T is a placeholder for the type. You can create an instance of a generic class by specifying type parameters. For example:

GenericClass intClass(10);
GenericClass strClass("Hello");

intClass.print();  // 输出:“Value:10”
strClass.print();  // 输出:“Value:Hello”

Practical case:

Consider an array containing student names. We can use generic classes to store and process different types of data, for example:

template 
class StudentArray {
public:
    StudentArray(size_t size) : arr(new T[size]) {}
    void add(T name, int index) {
        arr[index] = name;
    }
    void print() {
        for (size_t i = 0; i < size(); ++i) {
            std::cout << "Student " << (i + 1) << ": " << arr[i] << std::endl;
        }
    }
    size_t size() {
        return size_;
    }
private:
    T* arr;
    size_t size_;
};

int main() {
    StudentArray names(5);

    names.add("John", 0);
    names.add("Jane", 1);
    names.add("Peter", 2);
    names.add("Susan", 3);
    names.add("Thomas", 4);

    names.print();
}

This code creates a generic array containing 5 strings. It has the ability to add and print student names.

The above is the detailed content of How to implement generic classes in C++?. 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