2017-10-07 41 views
-1

我有一個基類和一個閉包,基類總是被特定的類擴展,但是它沒有確定基類具體包含的內容。在C++中使用閉包來改變行爲

現在我想重寫基類的行爲,同時改變特定類的行爲。

這裏是什麼,我想實現一個簡單的例子:

class base 
{ 
    public: 
     inline void print() 
     { 
      std::cout << "test!" << std::endl; 
     } 
}; 

template <class T> 
class closure 
{ 
    public: 
     inline closure() 
     { 
      if (!std::is_convertible<T*, base*>::value) { 
       throw "error!"; 
      } 

      this->baseInstance = new T(); 
     } 

     /* 
     * In this class the behavior of test should be extended/overridden. 
     * in this case base::print 
     */ 

     ~closure() 
     { 
      delete this->baseInstance; 
     } 

     inline T * operator->() 
     { 
      return this->baseInstance; 
     } 
    private: 
     T * baseInstance; 
}; 

class test : public base 
{ 
    public: 
     inline void otherStuff() 
     { 
      /* ... **/ 
     } 
     /* .. */ 
}; 

在這種情況下,我想重寫base::print(),但保持test::otherStuff()全部功能時,它就會通過關閉調用。

回答

0

好的,我自己找到了解決方案。

最後,這是很容易, 因爲我知道我想改變什麼功能, 我寫了基類的整體功能爲std::function<void()>,然後我friended關閉,這樣,就可以將其覆蓋。

base::print()方法調用得到了改變成std::function<void()>的號召,現在,它工作得很好。

相關問題