Without referring to a book, can anyone please provide a good explanation for CRTP
with a code example?
CRTP is a technique to implement compile-time polymorphism. Here's a very simple example. In the below example, ProcessFoo()
is working with Base
class interface and Base::Foo
invokes the derived object's foo()
method, which is what you aim to do with virtual methods.
http://coliru.stacked-crooked.com/a/2d27f1e09d567d0e
template
struct Base {
void foo() {
(static_cast(this))->foo();
}
};
struct Derived : public Base {
void foo() {
cout << "derived foo" << endl;
}
};
struct AnotherDerived : public Base {
void foo() {
cout << "AnotherDerived foo" << endl;
}
};
template
void ProcessFoo(Base* b) {
b->foo();
}
int main()
{
Derived d1;
AnotherDerived d2;
ProcessFoo(&d1);
ProcessFoo(&d2);
return 0;
}
Output:
derived foo
AnotherDerived foo