Location>code7788 >text

C++ Learning: What is the CRTP mode

Popularity:997 ℃/2025-02-05 19:13:17

CRTP (Curiously Recurring Template Pattern) is a design pattern in C++.

Basic concept

CRTP refers to a class (usually a base class)Use its derived class as template parametersMode. The basic form is as follows:

template <typename Derived>
 class Base {
 // Member functions of the base class can use the Derived type
 };

 class Derived : public Base<Derived> {
 // Definition of derived classes
 };

Main uses and advantages

  • Static polymorphism
    CRTP can be implementedStatic polymorphism, that is, the function to be called at compile time,avoidIt'sDynamic polymorphism(Implemented through virtual functions)Runtime overhead
template <typename Derived>
 class Shape {
 public:
 void draw() {
 static_cast<Derived*>(this)->drawImpl();
 }
 };
 class Circle : public Shape<Circle> {
 public:
 void drawImpl() {
 std::cout << "Drawing a circle" << std::endl;
 }
 };

 class Square : public Shape<Square> {
 public:
 void drawImpl() {
 std::cout << "Drawing a square" << std::endl;
 }
 };

 int Main () {
 Circle circle;
 Square square;
 (); // Call Circle's drawImpl
 (); // Call Square's drawImpl
 Return 0;
 }

In this example, the draw function of the Shape class converts this pointer to the Derived type via static_cast, and then calls the drawImpl function. Since the drawImpl function is determined at compile time, there is no overhead of virtual function calls.

  • Avoid virtual function overhead
    In some cases, calling virtual functions can bring some overhead, especially in performance-sensitive code. CRTP can be used as an alternative to avoid the use of virtual functions.
  • Code reuse and extension
    CRTP allows base classes to access members of derived classes, thereby implementing code reuse and extension. The base class can call the specific functions of the derived class without knowing the specific derived class.