【发布时间】:2016-02-28 17:42:47
【问题描述】:
我正在尝试在 C++ 中进行回调。回调的参数是一个通过引用传递的向量。问题是当我调用函数时,向量总是空的。为了证明这一点,请参见下面的程序。
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 打败了我。 cplusplus.com/reference/functional/bind 见那里的例子。