How do i write a pointer-to-member-function with std::function?

前端 未结 5 1124
刺人心
刺人心 2020-12-07 15:58

I know how to declare int fn(double) inside of std::function (std::function). I know how to write a pointer-to-member-function (

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 16:28

    A member function is not a function. It is not itself anything you can call. All you can do is call a member function of an instance object. Only the pair of pointer-to-member-function and object constitutes a callable entity.

    To bind an instance to a PTMF and obtain something callable, use bind:

    #include 
    
    struct Foo
    {
        double bar(bool, char);
    };
    
    Foo x;
    using namespace std::placeholders;
    std::function f = std::bind(&Foo::bar, x, _1, _2);
    f(true, 'a'); //...
    

    As with lambdas, bind expressions have an unknowable type, and the conversion to std::function (as well as the actual dispatch) is potentially expensive. If possible, it is preferable to use auto for the type of the bind expression.

提交回复
热议问题