What CRTP is
The CRTP consists in:
- inheriting from a template class
- use the derived class itself as a template parameter of the base class
This is what it looks like in code:
The purpose of doing this is using the derived class in the base class. From the perspective of the base object, the derived object is itself, but downcasted. Therefore the base class can access the derived class by static_casting
itself into the derived class.
What could go wrong
If two classes happen to derive from the same CRTP base class we likely get to undefined behaviour when the CRTP will try to use the wrong class:
There is solution to prevent this, that has been proposed by fluentcpp comment. It consists in adding a private constructor in the base class, and making the base class friend with the templated class.
Indeed, the constructors of the derived class have to call the constructor of the base class. Since the ctor in the base class is private, no one can access it except the friend classes. And the only friend class is … the template class! So if the derived class is different from the template class, The code doesn’t compile.
What the CRTP can bring to your code.
static(compile-time) polymorphism (vs dynamic polymorphism)
CRTP as a delegation pattern(static interface)
For example, auto generate the != operator
ref
- fluentcpp
- Hands-on Design Patterns with C++ Chapter 8