Home  >  Article  >  Backend Development  >  Do STL function objects support polymorphism? How to achieve?

Do STL function objects support polymorphism? How to achieve?

王林
王林Original
2024-04-25 10:39:01747browse

STL function objects support polymorphism, which is implemented as follows: use virtual functions and virtual inheritance to define abstract base classes and their derived classes. Define specific versions of functions for each derived class. Pass concrete classes as parameters to the algorithm.

STL 函数对象是否支持多态性?如何实现?

#Do STL function objects support polymorphism?

Function objects in the Standard Template Library (STL) support runtime polymorphism, allowing dynamic determination of which function to call during program execution.

Implementation method:

By using virtual functions and virtual inheritance, polymorphic function objects can be implemented.

Code Example:

Consider the following example, where an abstract base class Shape is defined with a pure virtual function area( ):

struct Shape {
  virtual double area() const = 0;
};

Concrete classes derived from Shape, such as Circle and Square, define their specific version area() Functions:

struct Circle : public Shape {
  double radius;

  Circle(double radius) : radius(radius) {}

  double area() const override {
    return M_PI * radius * radius;
  }
};

struct Square : public Shape {
  double side_length;

  Square(double side_length) : side_length(side_length) {}

  double area() const override {
    return side_length * side_length;
  }
};

These concrete classes can be passed as arguments to algorithms using function objects:

std::vector<Shape*> shapes{new Circle(2), new Square(3)};

double total_area = 0;
for (const auto& shape : shapes) {
  total_area += shape->area();
}

std::cout << "Total area: " << total_area << std::endl;

In this example, even shapes Pointers to different Shape derived classes are stored, and the polymorphic function object will also call the correct area() function.

Practical case:

Polymorphic function objects are very useful in dynamic scheduling and loosely coupled code, for example:

  • In graphics libraries ,Shape classes can represent different types of graphics. Polymorphic function objects allow areas to be drawn and calculated without modifying graphics code.
  • In database applications, connection classes can abstract different types of database connections. Polymorphic function objects allow queries and updates to be performed transparently.

The above is the detailed content of Do STL function objects support polymorphism? How to achieve?. 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