2014-10-09 53 views
1

C++存儲功能說你定義一個回調函數這樣:不用爭論

typedef std::function<void(float)> Callback; 

而且你有一個功能,例如:

void ImAFunction(float a) 
{ 
    //Do something with a 
} 

有沒有一種辦法能夠存儲沒有參數的函數然後傳遞給它一個?

像這樣的:

//Define the Callback storage 
Callback storage; 

storage = std::bind(ImAFunction, this); 

//Do some things 

storage(5); 

這是我的一些下面我真正的代碼解釋無法工作。

如果我將值與std :: bind函數綁定,我可以接近我想要的東西。如:

//Change 
//storage = std::bind(ImAFunction, this); 
storage = std::bind(ImAFunction, this, 5.0); //5.0 is a float passed 

這個工作,但是當我去通過函數傳遞一個值的結果是什麼我將其設置爲前:

storage(100); //Output is still 5 

我立足的事實,我認爲這是這篇文章可能。

http://www.cprogramming.com/tutorial/function-pointers.html

它不使用的功能或綁定功能,但是不會通過指針參數,並執行正是我需要的。我不只是跳過綁定函數的原因是因爲我試圖將該函數存儲在一個類(私有)中,並且如果它是模板是因爲它是用該類創建的,我無法存儲它。

上述製得的誤差來源於此代碼:

struct BindInfo { 
    Callback keyCallback; 
    int bindType; 
    bool isDown; 
    bool held; 
    std::string name; 
}; 

template <class T1> 
void bindEvent(int bindType, T1* keydownObj, void(T1::*keydownF)(float), std::string name) 
{ 
    BindInfo newKeyInfo = { std::bind(keydownF, keydownObj), bindType, false, false, name }; 

    inputBindings.insert(std::pair<int, BindInfo>(BIND_NULL, newKeyInfo)); 
}; 

錯誤是:

No viable conversion from '__bind<void(Main::*&)(float), Main *&>' to 'Callback' (aka 'function<void (float)>' 

這是可能的?提前致謝。

+2

你可能會尋找'的std ::綁定(ImAFunction,這,的std ::佔位符:: _ 1)' – 2014-10-09 02:49:25

回答

2

可以包括未綁定的參數的佔位符:

std::bind(&Main::ImAFunction, this, std::placeholders::_1); 

如果你發現有點拗口,拉姆達可能更可讀:

[this](float a){ImAFunction(a);} 
+0

完美的作品,謝謝。 – TrevorPeyton 2014-10-09 15:04:39

0

這聽起來像你'重新尋找是一個函數指針。雖然我在C++中沒有很多使用它們的經驗,但我已經在C中使用它們:是的,這是可能的。也許是這樣的:

void (*IAmAFunctionPointer)(float) = &IAmAFunction; 

,最好的辦法去想該行是,IAmAFunctionPointer是一個指針(因此*),它返回一個空白,並採取了浮動。然後:

float a = 5; 
IAmAFunctionPointer(a); 

你甚至可以設計它,使回調函數傳遞到方法(我認爲這是你要找的)。

void DoStuffThenCallback(float a, void (*callback)(float)) 
    { 
    //DoStuff 
    callback(a); 
    } 

進一步閱讀:http://www.cprogramming.com/tutorial/function-pointers.html

+0

這個問題是我不會知道類和函數,所以它必須是一個模板,然後才能存儲它。我無法存儲模板對象。 – TrevorPeyton 2014-10-09 14:54:40