Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Discussion

Demystifying C++ template Curiously Recurring Template Pattern (CRTP) for Static Polymorphism [StackOverflow Architecture Guide]

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rep: 124
Datum pridruživanja: Jun 2019
Postovi: 29
Hvala: 72
2 prije tjedana · Aug 6, 2026 4:06 AM
#1

How CRTP achieves polymorphic behavior without virtual table pointers (0 virtual dispatch overhead):

CPP
template<typename Derived>
class Base {
public:
    void Process() {
        static_cast<Derived*>(this)->ExecuteImpl();
    }
};

class Worker : public Base<Worker> {
public:
    void ExecuteImpl() { std::cout << "Worker processing\n"; }
};

The compiler resolves Process() calls at compile-time via static dispatch, allowing inlining with zero vtable pointer overhead (saving 8 bytes per instance)!

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rep: 47
Datum pridruživanja: Feb 2018
Postovi: 17
Hvala: 75
2 prije tjedana · Aug 6, 2026 7:17 AM
#2

CRTP is heavily used in high-frequency trading and game engines where virtual method calls in hot loops incur branch mispredictions.

llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
Rep: 139
Datum pridruživanja: Jul 2018
Postovi: 21
Hvala: 15
2 prije tjedana · Aug 6, 2026 8:15 PM
#3

In C++23, 'Deducing this' (explicit object parameters) makes CRTP even cleaner without template base class inheritance syntax!