What is the curiously recurring template pattern (CRTP)?

前端 未结 5 1823
小鲜肉
小鲜肉 2020-11-21 11:27

Without referring to a book, can anyone please provide a good explanation for CRTP with a code example?

5条回答
  •  既然无缘
    2020-11-21 12:16

    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);
        }
    };
    

提交回复
热议问题