什么是奇怪的重复模板模式(CRTP)?没有参考一本书,谁能给出一个很好的解释CRTP用一个代码示例?
3 回答
米脂
TA贡献1836条经验 获得超3个赞
template <class T>class Writer{
public:
Writer() { }
~Writer() { }
void write(const char* str) const
{
static_cast<const T*>(this)->writeImpl(str); //here the magic is!!!
}};class FileWriter : public Writer<FileWriter>{
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<ConsoleWriter>{
public:
ConsoleWriter() { }
~ConsoleWriter() { }
void writeImpl(const char* str) const
{
printf("%s\n", str);
}};- 3 回答
- 0 关注
- 625 浏览
添加回答
举报
0/150
提交
取消
