skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-crtp
This page is read only. You can view the source, but not change it.
# C++ CRTP **[CRTP](https://en.cppreference.com/w/cpp/language/crtp)** (Curiously Recurring Template Pattern) is a static polymorphism technique where a derived class passes itself as a template parameter to its base class. This enables zero-overhead polymorphism without virtual functions by allowing the base to call derived implementations at compile time. Use CRTP when you need polymorphic behavior without the runtime cost of virtual function calls. ## Example This example shows how CRTP allows a base class to call derived methods without virtual functions. ```cpp // compile: g++ -o crtp crtp.cpp // run: ./crtp // description: static polymorphism via CRTP without virtual dispatch #include <iostream> template <typename Derived> class Shape { public: void draw() { static_cast<Derived*>(this)->drawImpl(); } }; class Circle : public Shape<Circle> { public: void drawImpl() { std::cout << "Drawing circle\n"; } }; class Square : public Shape<Square> { public: void drawImpl() { std::cout << "Drawing square\n"; } }; int main() { Circle c; c.draw(); Square s; s.draw(); return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top