Without referring to a book, can anyone please provide a good explanation for CRTP
with a code example?
Here you can see a great example. If you use virtual method the program will know what execute in runtime. Implementing CRTP the compiler is which decide in compile time!!! This is a great performance!
template
class Writer
{
public:
Writer() { }
~Writer() { }
void write(const char* str) const
{
static_cast(this)->writeImpl(str); //here the magic is!!!
}
};
class FileWriter : public Writer
{
public:
FileWriter(FILE* aFile) { mFile = aFile; }
~FileWriter() { fclose(mFile); }
//here comes the implementation of the write method on the subclass
void writeImpl(const char* str) const
{
fprintf(mFile, "%s\n", str);
}
private:
FILE* mFile;
};
class ConsoleWriter : public Writer
{
public:
ConsoleWriter() { }
~ConsoleWriter() { }
void writeImpl(const char* str) const
{
printf("%s\n", str);
}
};