How it works with CRTP - GerdHirsch/Cpp-TemplateFactoryMethod GitHub Wiki
CRTP Corriously Recuring Template Pattern
this is a strange name, but it means inherit from a template and the argument is the class itself!
class Application : public Implementation<Application>{..};
Name shadowing vs. virtual
The derived type Application
is known at compile-time in the base-class
Implementation
via template parameter ConcreteApplication
. Hence this
can be static casted: static_cast<ConcreteApplication*>(this)
done in Method This()
. To make clear what it is, the alias using this_type = ConcreteApplication;
is defined and used in the cast instead of the name of the parameter.
To access a member of a template use this->
, but this
is the scope of the class where it´s used, in this case Implementation<Application>
.
To access a member of the derived class Application
, use This()->
which casts this
to this_type
as described above.
Because This()
is of type Application*const
, the name resolution starts in that scope with the consequence, all names from the outer scope e.g. the base-class are hidden, if the name is used in any way in the derived-class.
With using base_type = Implementation<Application>;
we can have a using declaration using base_type::name
, which expands the scope, where the name is searched for.
With this in place in the derived-class, the name of e.g. a overloaded method witch one of them is overridden in the derived-class, the overloads from base-class will be found.
This()->overloadedAndOverriddenMethod(42)
in this Version named HookMethod2(int)
with an overload HookMethod2()
which is overridden in Application
and called in base-class Implementation::TemplateMethod()
.
Template Method Pattern with CRTP