Understanding std::function and std::bind

前端 未结 2 757
春和景丽
春和景丽 2021-02-15 05:23

I was playing arround with std::function and std::bind and I noticed something unintuitive and I would like to understand it better.

For example:

void fu         


        
2条回答
  •  孤街浪徒
    2021-02-15 05:51

    If you don't use argument placeholders (_1, _2, ...), then any arguments passed to the function object returned from std::bind will just be discarded. With:

    std::function f = std::bind(fun, std::placeholders::_1);
    

    I get a (long and ugly) error as expected.

    For the people interested in Standardese:

    §20.8.9.1.2 [func.bind.bind]

    template
    *unspecified* bind(F&& f, BoundArgs&&... bound_args);
    

    p3 Returns: A forwarding call wrapper g with a weak result type (20.8.2). The effect of g(u1, u2, ..., uM) shall be INVOKE(fd, v1, v2, ..., vN, result_of::type), where cv represents the cv-qualifiers of g and the values and types of the bound arguments v1, v2, ..., vN are determined as specified below.

    p10 The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows:

    • if TiD is reference_wrapper, the argument is tid.get() and its type Vi is T&;
    • if the value of is_bind_expression::value is true, the argument is tid(std::forward(uj)...) and its type Vi is result_of::type;
    • if the value j of is_placeholder::value is not zero, the argument is std::forward(uj) and its type Vi is Uj&&;
    • otherwise, the value is tid and its type Vi is TiD cv &.

提交回复
热议问题