This is a follow up questions from Static polymorphism in C++
When should I prefer duck typing?
When should I prefer CRTP?
Are there any best practices?
It would boil down to this:
template<typename T>
void print_renderer(const renderer<T> &r){
r.get();
}
vs
template<typename T>
void print_renderer(const T &r){
static_assert(is_renderer<T>,"Not a renderer");
r.get();
}
What I have observed so far:
CRTP is not as nice to use as run-time polymorphism. To create an polymorphic interface someone has just to use
virtual
andoverride
. Both of these keywords can't be used with CTRP. If I I have a typo in my implementation it will trigger a run-time error. (Maybe this can be prevented)Duck typing is really simple but it may confuse my clients. If they don't have access to the source code and they have to use
void print_renderer(T r)
vsvoid print_renderer(renderer<T> r)
I think CRTP is much clearer.Duck typing does have a maintaining cost. In my previous question I created an
open_gl
anddirect_draw
implementation for my renderer. If I wanted to add another renderer for exampleopen_gl_es
, I would also have to change myis_renderer<T>
function. But I don't think it would be too bad.