C ++ std :: vector作为std :: function

时间:2016-02-28 17:42:48

标签: c++ function vector

我试图用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”,但没有打印。

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

那么这里出了什么问题?非常感谢任何帮助或提示。感谢。

2 个答案:

答案 0 :(得分:5)

当你写:

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

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

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

map[ "test1" ] = TestFunction;

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

答案 1 :(得分:1)

您需要bind TestFunctionvector。您可以直接将其添加到地图中。

map[ "test1" ] = TestFunction;
map[ "test2" ] = TestFunction;
相关问题