2016-02-28 294 views
0

我正在嘗試在C++中進行回調。回調的參數是一個通過引用傳遞的向量。問題是當我調用函數時,矢量總是空的。爲了演示這一點,請參閱下面的程序。C++ std :: vector作爲std :: function的參數

struct TestStruct { 
    int x; 
    int y; 
}; 

void TestFunction(const std::vector<TestStruct> &vect) { 
    for (unsigned int i = 0; i < vect.size(); i++) { 
     printf("%i, %i\n", vect[ i ].x, vect[ i ].y); 
    } 
} 

int main() { 
    std::map<std::string, std::function<void(const std::vector<TestStruct>&)>> map; 

    std::vector<TestStruct> vect; 
    map[ "test1" ] = std::bind(&TestFunction, vect); 
    map[ "test2" ] = std::bind(&TestFunction, vect); 

    std::vector<TestStruct> params; 
    TestStruct t; 
    t.x = 1; 
    t.y = 2; 
    params.emplace_back(t); 

    map[ "test1" ](params); 
} 

這是我所能做的最接近的例子。我已經在地圖中保存了回調。然後我將這些函數添加到地圖中。然後我製作一個通用的TestStruct並將其放入我的參數中。最後,我打電話給該功能,它應該打印出「1,2」,而不是打印。

當我調試它說它的參數是空的。這導致我相信我做錯了什麼或者這是不可能的。

那麼這裏出了什麼問題?任何幫助或提示,不勝感激。謝謝。

+1

你想要用'std :: placeholders :: _ 1',而不是'vect',即'std :: bind(&TestFunction,std :: placeholders :: _ 1);',或者實際上'map [ 「test1」] =&TestFunction;'應該足夠了(沒有'bind') –

+0

@Piotr擊敗了我。 http://www.cplusplus.com/reference/functional/bind/看到那裏的例子。 – Matt

回答

4

當你寫:

map[ "test1" ] = std::bind(&TestFunction, vect); 

這就給了你一個無參函數,調用它時,讓你的TestFunction(vect)結果。你是綁定 ing vect到第一個參數TestFunction。所以當你打電話給它時,你打印的是vect(這是空的)的結果,而不是params(不是)的結果。

那是不是你想要的所有 - 你想要的實際功能TestFunction

map[ "test1" ] = TestFunction; 

你可能會認爲這不會編譯。畢竟,你需要一個接受參數的函數,但是你給了它一個不帶參數的函數。但bind()只是忽略它不使用的所有參數。

1

您並不需要bindTestFunction並且空的vector。您可以直接將其添加到地圖。

map[ "test1" ] = TestFunction; 
map[ "test2" ] = TestFunction; 
+0

完美地工作,謝謝! – CMilby