Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

template
pattern
c++

What is the curiously recurring template pattern?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The curiously recurring template pattern (CRTP) occurs when a child class has a parent class that is a template specialization for that class.

Based on the parameter that is passed during the function call, the compiler determines which function will be called – this is called compile-time polymorphism. CRTP is primarily used to implement compile-time polymorphism.

Syntax

This is what CRTP looks like:

svg viewer
Syntax in C++

Implementation

The following code uses CRTP to implement compile-time polymorphism:

#include <iostream>
using namespace std;
// Note that no virtual functions are required in compile-time
// polymorphism.
template <typename T>
// This is the parent class. It takes a template parameter
class Citrus {
public:
void description() {
static_cast<T*>(this) -> description();
}
};
// This is the child class. Signature of CRTP: Child class is passed
// as a template parameter to the parent class.
class Clementine : public Citrus<Clementine>
{
public:
void description() {
cout << "I am a Clementine." << endl;
}
};
// This is the child class. Signature of CRTP: Child class is passed
// as a template parameter to the parent class.
class Lime : public Citrus<Lime>
{
public:
void description() {
cout << "I am a Lime." <<endl;
}
};
// A function that calls the appropriate methd based on the argument.
template <typename T>
void fruit_description(Citrus<T> citrus) {
citrus.description();
}
int main() {
Clementine clementine;
Lime lime;
fruit_description(clementine);
fruit_description(lime);
return 0;
}

RELATED TAGS

template
pattern
c++
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring