我正在尝试在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”,而不是打印。
当我调试它说它的参数是空的。这导致我相信我做错了什么或者这是不可能的。
那么这里出了什么问题?任何帮助或提示,不胜感激。谢谢。
你想要用'std :: placeholders :: _ 1',而不是'vect',即'std :: bind(&TestFunction,std :: placeholders :: _ 1);',或者实际上'map [ “test1”] =&TestFunction;'应该足够了(没有'bind') –
@Piotr击败了我。 http://www.cplusplus.com/reference/functional/bind/看到那里的例子。 – Matt