I have a performance critical piece of code for which I am considering using the CRTP. My question is to what extent most compilers are able to optimize the code. In particular I am wondering if the compiler can inline (when appropriate) methods. For example, in the following code:
template <class Derived>
struct Base
{
void interface()
{
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
};
struct Derived : Base<Derived>
{
void implementation();
};
would a call to object.interface() yield the same performance as a call to object.implementation()
With optimization turned on, and if the compiler considers this to be worth inlining, yes.
What’s good in CRTP compared to dynamic dispatch, is that from compiler’s point of view it’s a regular function call.