2014-01-28 73 views
6

我想存儲一個函數以後再調用,這裏是一個片段。std ::在類內部綁定一個靜態成員函數

這工作得很好:

void RandomClass::aFunc(int param1, int param2, double param3, bool isQueued /*= false */) 
{ 
    /* If some condition happened, store this func for later */ 
    auto storeFunc = std::bind (&RandomClass::aFunc, this, param1, param2, param3, true); 

    CommandList.push(storeFunc); 

    /* Do random stuff */ 
} 

但是,如果RandomClass是靜態的,所以我相信我應該這樣做:

void RandomClass::aFunc(int param1, int param2, double param3, bool isQueued /*= false */) 
{ 
    /* If some condition happened, store this func for later */ 
    auto storeFunc = std::bind (&RandomClass::aFunc, param1, param2, param3, true); 

    CommandList.push(storeFunc); 

    /* Do random stuff */ 
} 

但是,這並不工作,我得到的編譯錯誤

錯誤C2668:'std :: tr1 :: bind':對超載函數的模糊調用

任何幫助讚賞。

+2

是否有多於一個的過載' RandomClass :: aFunc'? – juanchopanza

+0

另外我可以做到這一點,它適用於普通類,但不適用於靜態版本。 \t CommandList.push([=]() \t { \t \t aFunc(參數1,參數2,參數3,TRUE); \t}); –

+0

是的,還有第二個:: aFunc具有不同的參數。另一個函數使用字符串,與我試圖使用的參數相比,它的參數更少。 –

回答

14

類型的指針的靜態成員函數的看起來像一個指針指向一個非成員fuinction:

auto storeFunc = std::bind ((void(*)(WORD, WORD, double, bool)) 
           &CSoundRouteHandlerApp::MakeRoute, 
           sourcePort, destPort, volume, true); 

下面是一個簡化的例子:

struct Foo 
{ 
    void foo_nonstatic(int, int) {} 
    static int foo_static(int, int, int) { return 42;} 
}; 

#include <functional> 
int main() 
{ 
    auto f_nonstatic = std::bind((void(Foo::*)(int, int))&Foo::foo_nonstatic, Foo(), 1, 2); 
    auto f_static = std::bind((int(*)(int, int, int))&Foo::foo_static, 1, 2, 3); 

} 
+0

這正是需要的,非常感謝! –

+0

我不能upvote你或者出於某種原因將其標記爲答案。如果有人可以,請將其標記爲正確。 –

+0

@StaetonGrey我認爲你可以將它標記爲答案,但你需要更多的代表點才能投票。 – juanchopanza