Search⌘ K
AI Features

Solution: CRTP-derived Class Restriction

Explore how the Curiously Recurring Template Pattern (CRTP) enforces restrictions on derived classes in C++ by using a private base class constructor. Understand why only the intended derived class can invoke the base constructor and how this prevents unintended class instantiations for better type safety and design clarity.

We'll cover the following...

Solution

C++
#include <iostream>
template <typename Derived>
struct Base{
void interface(){
static_cast<Derived*>(this)->implementation();
}
private:
Base() = default;
friend Derived;
};
struct Derived1: Base<Derived1>{
void implementation(){
std::cout << "Implementation Derived1" << '\n';
}
};
struct Derived2: Base<Derived2>{
void implementation(){
std::cout << "Implementation Derived2" << '\n';
}
};
template <typename T>
void execute(T& base){
base.interface();
}
int main(){
std::cout << '\n';
Derived1 d1;
execute(d1);
Derived2 d2;
execute(d2);
std::cout << '\n';
}

Explanation

  • Lines 8–9: We defined a private base class constructor. Because it’s private, only a
...