Compile errors using std::bind in gcc 4.7

后端 未结 2 1831
遥遥无期
遥遥无期 2021-01-16 08:53

I am having a lot of trouble using std::bind in various places of my code. Sometimes it works, sometimes it doesn\'t, so I assume I am doing something fundament

相关标签:
2条回答
  • 2021-01-16 09:16

    The placeholder position objects (e.g. when you use _2) is not the position of the argument in the function you call, but a placeholder for the argument in the created callable object. Instead always start with _1 and increase.

    So:

    auto bar_auto=std::bind(foo,1,_1);
    

    etc.


    This means you can switch the arguments in the object created by std::bind by simply doing like

    auto bar_auto=std::bind(foo,_2,_1);
    

    When you "call" the bar_auto object, the first argument will be the second argument to foo, and the second argument in the call will be the first argument to foo.

    0 讨论(0)
  • 2021-01-16 09:21

    The _2 placeholder means to use second argument of the returned functor. Therefore the type of

    std::bind(foo,1,_2)
    

    is not std::function<int(int)> but

    std::function<int(unspecified_type, int)>
    

    To get std::function<int(int)>, use

    std::bind(foo, 1, _1)
    //                ^^
    
    0 讨论(0)
提交回复
热议问题