亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

什么是奇怪的重復模板模式(CRTP)?

什么是奇怪的重復模板模式(CRTP)?

C++ C
慕的地6264312 2019-06-12 15:04:31
什么是奇怪的重復模板模式(CRTP)?沒有參考一本書,誰能給出一個很好的解釋CRTP用一個代碼示例?
查看完整描述

3 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

這里你可以看到一個很好的例子。如果使用虛擬方法,程序將知道運行時執行的是什么。實現CRTP編譯器是在編譯時決定的!這是一場精彩的表演!

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


查看完整回答
反對 回復 2019-06-12
  • 3 回答
  • 0 關注
  • 606 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號