Home > Article > Backend Development > Do STL function objects support polymorphism? How to achieve?
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.
#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:
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!