As part of system design, we need to implement a factory pattern. In combination with the factory pattern, we also use CRTP to provide a basic set of functions that can then be configured with Derived classes.
Sample code below:
class FactoryInterface{ public: virtual void doX() = 0; }; //force all derived classes to implement custom_X_impl template< typename Derived, typename Base = FactoryInterface> class CRTP : public Base { public: void doX(){ // do common processing..... then static_cast<Derived*>(this)->custom_X_impl(); } }; class Derived: public CRTP<Derived> { public: void custom_X_impl(){ //do custom stuff } };
Although this design is confusing, it offers several advantages. All calls after calling the initial virtual function can be embedded. Calling the derived class custom_X_impl is also efficient.
I wrote a comparison program to compare behavior for a similar implementation (hard loop, callbacks) using function pointers and virtual functions. This design was a triumph for gcc / 4.8 with O2 and O3.
However, as a C ++ consultant told me yesterday, any call to a virtual function in a large runtime program can take variable time, given cache misses, and I can achieve potentially better performance using the C-style table function tables and gcc function hot lists. However, I still see 2x cost in my sample program mentioned above.
My questions: 1. Is the statement of the guru true? For any answers, are there any links I can link to. 2. Is there any low latency implementation that I can reference that has a base class that calls a user-defined function in a derived class using function pointers? 3. Any suggestions for improving the design?
Any other feedback is always welcome.
c ++ gcc low-latency class-design crtp
Sid
source share