C++ std::vector 作为 std::function 的参数

C++ std::vector as Parameter for std::function

本文关键字:std function 参数 vector C++ 作为      更新时间:2023-10-16

>我试图在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, %in", 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",但不打印任何内容。

当我调试它时,它说参数为空。这让我相信我做错了什么,或者这是不可能的。

那么这里出了什么问题呢?任何帮助或提示将不胜感激。谢谢。

当你写:

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

这为您提供了一个空函数,当调用该函数时,它会为您提供TestFunction(vect)的结果。您正在将vect绑定TestFunction 的第一个参数。因此,当您调用它时,您正在打印vect中的内容(为空)的结果,而不是params中的内容(不是)。

这根本不是你想要的 - 你想要实际的功能TestFunction

map[ "test1" ] = TestFunction;
<小时 />

你会认为这不会编译。毕竟,你想要一个接受参数的函数,但你给了它一个不接受参数的函数。但是bind()只是忽略了它不使用的所有参数。

您不需要使用空vector bind TestFunction。您可以直接将其添加到地图中。

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