In the last post I showed how to shrink the vtable overhead and reduce the coupling of the framework.
This time I shall show how to reduce the vtable hit even further using another technique called the Curiously Recurring Template Pattern or CRTP. This oddly name pattern is a way of replacing runtime virtual calls with compile time dispatch. It achieves this by passing the derived class type as a template type parameter to the base class.
By the use of this technique, the base class can be informed of its concrete type at compile time. This allows the base type to directly call member functions in the derived type thereby avoiding an indirect call though the vtable. If the called functions are deemed suitable by the compiler, then they may well be inlined too.
This is the technique that we will use for the third version of the messaging framework.
The messages are defined in the same way as before.
As is the base message processor interface.
The difference now is in the definitions of the templated message handlers. The derived message processor type is passed as a template type parameter and used to cast the ‘this’ pointer to the true concrete type, allowing direct calls to the handler functions.
The derived message processors are very similar to before, with the exception that the derived class is passed as template type parameter to the base.
We now have a message framework where the processor classes contain just one virtual function and where calls to the handler functions are direct.
The tests are defined exactly as in every previous version of the framework, as is the output.
Processor1 : Message1 Processor1 : Message2 Processor1 : Message3 Processor1 : Message4 Processor2 : Message1 Processor2 : Unhandled IMessage Processor2 : Message3 Processor2 : Unhandled IMessage
Chain Of Responsibility
If the ability to set a successor message processor is added to IMessageProcessor, the framework is then able to implement the Chain Of Responsibility design pattern.
A version of this framework can be found as part of the Embedded Template Library, an open source C++ library distributed under the MIT licence.