0

我努力創建派生類並將方法指針從它傳遞給基類,以便在基類中聲明的函數可以調用它(通過接口調用派生類的函數)。傳遞和投射方法指針

目標是創建派生類來引入它們自己的資源和函數,但是通過在基類提供的函數中調用其中一個函數來調用函數應該是可能的。爲此,我需要將派生的成員函數指針傳遞給基類。

這裏是我的嘗試:

class KeyFunction 
{ 
    void(*KeyFunction::KeyFuncPtr)() = nullptr; //pointer to a method of this class to store standard behavior for call 

public: 
    KeyFunction(void(*KeyFunction::KeyFunc)()) : KeyFuncPtr(KeyFunc) {}     //constructor which takes in standard behavior 

    void func()  //standard call of the function 
    { 
     if(KeyFuncPtr)KeyFuncPtr(); //call with ensurance there's something to be called 
    } 

    void operator()() //make KeyFunction class callable 
    { 
     func(); 
    } 
}; 

class customRessource{ 
public: 
    string up = "UP"; 
    string down = "DOWN"; 

}; 

class customKeyFunc : public KeyFunction 
{ 
    customRessource& r; 
public: 
    void moveup()    //possible behavior 
    { 
     cout << r.up; 
    } 
    void movedown() 
    { 
     cout << r.down; 
    } 

    customKeyFunc(void(*customKeyFunc::KeyFunc)()) :KeyFunction((void(*KeyFunction::)()) (KeyFunc)){} 


}; 

int main() 
{ 
    customKeyFunc Up(&(customKeyFunc::moveup)); //setup functions 
    customKeyFunc Down(&customKeyFunc::movedown); 

    Up();           //call functions 
    Down(); 

    getchar(); 
    return 0; 
} 

末主要功能顯示了應該的方式來使用類。

首先:我在每個類的構造函數中的類型都是瘋狂的(我嘗試了很多關於如何編寫成員指針的搜索,但我仍然不太穩定) 有人可以幫助我獲得它們對 ?

我可以做到這一點(尤其是像我在customKeyFunc構造函數中一樣強制轉換成員指針)嗎?我是以正確的方式解決這個問題,還是我覺得太複雜了?

非常感謝您的幫助!

+1

看起來像你對我正試圖重塑虛擬方法。重新創造輪子總是一項艱鉅的工作。 –

+1

看起來像[CRTP]的用例(https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) – Rerito

+0

有沒有你不使用虛函數的原因? – ShuberFu

回答

1

這樣的事情?

#include <functional> 
#include <string> 
#include <iostream> 

class customResource{ 
public: 
    const std::string up = "UP"; 
    const std::string down = "DOWN"; 
}; 

class customKeyFunc 
{ 
    const customResource& r; 
public: 
    customKeyFunc(const customResource& r) : r(r) {} 

    void moveup()    //possible behavior 
    { 
     std::cout << r.up; 
    } 

    void movedown() 
    { 
     std::cout << r.down; 
    } 

}; 

int main() 
{ 
    customResource r; 
    customKeyFunc f(r); 

    auto Up = std::function<void()>(std::bind(&customKeyFunc::moveup, f)); 
    auto Down = std::function<void()>(std::bind(&customKeyFunc::movedown, f)); 

    Up();           //call functions 
    Down(); 

    return 0; 
} 

std::function<void()>是一個多態函數對象,將複製任何對象:

  • 是可移動的或可複製,並

  • 實現void operator()

+0

我會試試這個 – Meph

+0

是的,這是完美的作品!真棒,謝謝你; D我現在可以定義一個具有這個功能的數組類,這是基本上我想創建它似乎。 – Meph

+0

對於協議:對於問題本身的實際解決方案可能是研究std文件有關std ::函數我猜(如果有人真的想自己做這個) – Meph