2012-09-13 43 views
6

說我有可能要指向這3個不同的功能:使用的std ::函數作爲一個委託C++ 11

float test1(int a, int b) { 
    return 7.0f; 
} 

struct TestClass { 
    float test2(int a, int b) { 
     return 5.0f; 
    } 
}; 

struct TestClass2 { 
    float test3(int a, int b) { 
     return 3.0f; 
    } 
}; 

通知所有三個如何使用相同的參數和返回值。我想抽象出它是否是一個成員函數以及它屬於哪個類。我想要一個委託類型,它可能指向這三個函數中的任何一個,這僅取決於它的初始化方式。

這是我第一次嘗試:

typedef std::function<float(int, int)> MyDelegate; // is this right? 

int main() { 
    TestClass obj; 
    TestClass2 obj2; 

    MyDelegate a = test1; 
    MyDelegate b = std::bind(std::mem_fn(&TestClass::test2), obj); // is this right? 
    MyDelegate c = std::bind(std::mem_fn(&TestClass2::test3), obj2); // is this right? 

    return 0; 
} 

的想法是我想還可以存儲在包裝內this指針了。這樣一來,它就像一個功能齊全的delegate.For例如,調用「B(X,Y)」應該是這樣調用obj.test2(x, y)

我甚至不能讓它編譯,我可能沒有完全抓住了這個。我對這些庫很陌生,VS2012中的錯誤是災難性的無用的。任何幫助,將不勝感激。

+0

的可能重複的[C++ 11個風格的回調?](http://stackoverflow.com/questions/12338695/c11-styled-callbacks) – Klaim

回答

9

你需要告訴std::bind做什麼與其他功能參數。爲了使呼叫b(x, y)委託xy你需要使用佔位符從std::placeholders命名空間中的兩個原始功能參數:

std::bind(&TestClass::test2, obj, std::placeholders::_1, std::placeholders::_2); 

還有還有沒有必要std::mem_fn(它的工作原理,雖然),因爲std::bind已經正確處理的成員函數(使隱this參數的顯式的第一個參數,像std::mem_fn一樣)。

3

您需要提供2個參數標準::綁定或提供佔位符後,爲他們提供 :

std::function<float(int, int)> c = std::bind(&TestClass2::test3, obj2, 1, 2); 
c(); //returns result 

OR

std::function<float(int, int)> c = std::bind(&TestClass2::test3, obj2, std::placeholders::_1, std::placeholders::_2); 
c(1, 2); //returns result 

更多信息有關的std ::綁定是here

2

使用Visual C++編譯器(CTP 2012)我窺探他們是如何做到的std ::功能和deliviered自己的解決方案來處理成員函數

用法是這樣的: http://ideone.com/v5zfDn

class Window 
{ 
public: 
    void Show(int number) const 
    { 
     //... 
    } 

    void ShowDynamic(int number) volatile 
    { 
     //... 
    } 
}; 

void ShowWindows(int param) 
{ 
    //... 
} 

int main() 
{ 
    Window window; 

    typedef mezutils::Delegate< void(int) > Notifier; 
    Notifier notifier; 

    notifier = &ShowWindows; 
    notifier(0); 

    notifier = Notifier(&window, &Window::Show); 
    notifier(1); 

    notifier = [](int x) { /*...*/ }; 
    notifier(2); 

    void (*funpc)(int) = func; 
    notifier = funpc; 
    notifier(3); 

    notifier = [](int arg) { printf("asd %d\r\n",arg); }; 
    notifier(4); 
    return 0; 
} 

委託類長相像: http://ideone.com/DebQgR

當然

是爲了好玩做了一個原型,但我喜歡它,因爲它很清楚

相關問題