To tzw. static polymorphism, a ściśle CRTP w C++ - trochę o tym pisze w internecie, na przykład http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism albo http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern.
#include <iostream>
template <class Derived>
struct Base
{
void generic_alg()
{
interface("aaaa");
interface("bbbb");
}
void interface(const char *c)
{
((Derived*)this)->implementation(c);
}
};
struct DerivedA : Base<DerivedA>
{
void implementation(const char *c)
{ std::cout << "cout << " << c << " << endl;" << std::endl; }
};
struct DerivedB : Base<DerivedB>
{
void implementation(const char *c)
{ std::cout << "puts(" << c << ");" << std::endl; }
};
int main()
{
DerivedA a;
a.generic_alg();
DerivedB b;
b.generic_alg();
}
Osiągasz dzięki temu quasi-polimorfizm (klasa bazowa może korzystać z dziedziczonej jak w przykładzie), a jednocześnie kod wykonuje się bez żadnej straty wydajności. Nie jest to oczywiście cudowne rozwiązanie wszystkich problemów, ale czasami przydatna sztuczka