The standard Template Method Pattern is well-known. For example, here is the pattern applied to a
toy case involving language translation:
If Print() isn't inlined, you will only have one copy of the common code in program memory.
If Print() is inlined, the optimizer may be able to combine this common code with code local
to the call of Print() and improve performance. This can be useful, but now imagine that you
are working on a real-time application and there are dozens or more virtual function calls inside
Print(). It would be nice to have a different version of Print() created for
each leaf class and make only a single virtual call to select the correct Print().
Alternative
Here is a version of the above hierarchy that accomplishes the same code reuse but scales better with increasing
number of sub-functions:
At first glance the UML diagram looks more complicated but there is really only one template class
added...the instantiated classes shown are simple typedefs. This code works exactly
the same as the original, and even behaves similarly under common mistakes like omitting or misspelling
a sub-function in one of the helper classes (which is not to say that either behave well).
There is one key (and unfortunate) difference that appears in the Print() function.
Because the sub-functions and members of Base are members of the dependent class T,
they must be prefixed by this-> when used. Alternately you can provide a using
declaration for the sub-functions and any members you use; this leaves Print() unchanged
from the original but is not supported by some older compilers. A using declaration or explicit
scoping will also bypass any virtual function calls, but that isn't likely to be a problem if you are using
this mechanism to eliminate such calls.