Content deleted Content added
m fmt |
|||
Line 17:
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
// ...
Derived::static_sub_func();
// ...
// ...
}
Line 24 ⟶ 33:
{
void implementation();
static void static_sub_func();
};
This technique achieves a similar effect to the use of virtual functions, without the costs (and some flexibility) of dynamic polymorphism. This particular use of the CRTP has been called "simulated dynamic binding" by [http://www.pnotepad.org/devlog/archives/000083.html some]. This pattern is used extensively in the Windows [[Active Template Library|ATL]] and [[WTL]] libraries.
To be more explicit about the above example, let us consider the case where we have a base class with '''no virtual functions'''. Whenever the base class calls another member function, it will always call its own base class functions. When we inherit from this class, a derived class, we inherit all the member variables and member functions that weren't overridden (no constructors or destructors, of course, either). If the derived class calls an inherited function that then calls another member function, it will never call any derived member functions. As a result of this behaviour, most C++ programmers define member functions as virtual to avoid this problem. Unfortunately, this can't be applied to static functions.
However, if base class member functions use the CRTP pattern for all member function calls, the overridden functions in the derived class will get selected at compile time. This effectively emulates the virtual function call system without the costs in size or function call overhead ([[VTBL]] structures, and method lookups, multiple-inheritance VTBL machinery).
|