The Curiously Recurring Template Pattern (CRTP) is a design pattern in C++ that involves creating a template class that inherits from a base class that is itself a template parameterized on the derived class. The derived class is then able to inherit functionality from the base class through the use of static polymorphism.
The primary benefit of using CRTP is improved performance. Since the derived class inherits from the base class, the compiler is able to inline the base class functions, resulting in faster execution times. Additionally, because the CRTP uses static polymorphism, there is no runtime overhead associated with virtual function calls.
Here is an example of using CRTP to implement a basic logging system:
template<typename Derived>
class Logger {
public:
void log(const std::string& message) {
static_cast<Derived*>(this)->doLog(message);
}
};
class FileLogger : public Logger<FileLogger> {
public:
void doLog(const std::string& message) {
// log message to file
}
};
class ConsoleLogger : public Logger<ConsoleLogger> {
public:
void doLog(const std::string& message) {
// log message to console
}
};
In this example, the Logger class is a template class that takes a single template parameter, Derived, which is the derived class that will inherit from the Logger class. The Logger class defines a single public function, log(), which takes a std::string message and passes it on to the derived class’s implementation of the doLog() function.
The FileLogger and ConsoleLogger classes both inherit from the Logger class, passing themselves as the template parameter. They each implement the doLog() function to log the message to either a file or the console, respectively.
Using CRTP in this way allows for easy implementation of a logging system with different output targets, while still achieving high performance due to the use of static polymorphism and inlining.