Curiously recurring template pattern: Difference between revisions

Content deleted Content added
Drudru (talk | contribs)
m utilize syntax highlighting
Line 2:
 
==Example==
<source lang="cpp">
// The Curiously Recurring Template Pattern (CRTP)
struct derived : base<derived>
{
{
// ...
// ...
};
</source>
 
Typically, the base class template will take advantage of the fact that member function bodies (definitions) are not instantiated until long after their declarations, and will use members of the derived class within its own member functions, via the use of a <code>static_cast</code>, or simply a cast e.g.:
 
<source lang="cpp">
template <class Derived>
struct base
{
{
void interface()
void {interface()
{
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
Derived::static_sub_func();
// ...
}
};
 
static void interfacestatic_func()
struct derived : base<derived>
{
void implementation();// ...
static void Derived::static_sub_func();
// ...
};
{}
};
 
struct derived : base<derived>
{
void implementation();
static void static_funcstatic_sub_func();
};
</source>
 
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.