How do i use CRTP in C++ to prevent the overhead of virtual member functions?
You will find two ways.
The first is as simple as indicating the interface statically for that structure of types:
template <class Derived> struct base struct my_type : base<my_type> needed to compile. struct your_type : base<your_type> needed to compile.
The 2nd the first is by staying away from using the reference-to-base or pointer-to-base idiom and perform the wiring at compile-time. While using above definition, you could have template functions that appear to be such as these:
template <class T> // Its deduced at compile-time void bar(base<T> &lifier obj) is going to do static dispatch struct not_derived_from_base // notice, not based on base // ... my_type my_instance your_type your_instance not_derived_from_base invalid_instance bar(my_instance) // will call my_instance.foo() bar(your_instance) // will call your_instance.foo() bar(invalid_instance) // compile error, cannot deduce correct overload
So mixing the dwellingOruser interface definition and also the compile-time type deduction inside your functions enables you to definitely do static dispatch rather than dynamic dispatch. This is actually the essence of static polymorphism.
I have been searching for decent discussions of CRTP myself. Todd Veldhuizen's Approaches for Scientific C++ is a superb resource with this (1.3) and several other advanced techniques like expression templates.
Also, I discovered you could read the majority of Coplien's original C++ Gems article at Google books. Maybe that's still the situation.
This Wikipedia answer has all that's necessary. Namely:
template <class Derived> struct Base static void static_func() struct Derived : Base<Derived>
Although I'm not sure just how much this really buys you. The overhead of the virtual function call is (compiler dependent, obviously):
- Memory: One function pointer per virtual function
- Runtime: One function pointer call
As the overhead of CRTP static polymorphism is:
- Memory: Duplication of Base per template instantiation
- Runtime: One function pointer call + whatever static_cast does
By way of strangely enough recurring template pattern you are able to implement the static polymorphism. You'll find a good example on wikipedia.