Search code examples
c++std-function

Explain me about std::function handling by class member method


#include <iostream>
#include <functional>

class world
{
public:
    void hello(){
        std::cout << "wow" << std::endl;
    }   
};
int main(void)
{
    std::function<world&,void()> pFn = &world::hello; //is this right???
};

I tried this, but it doesn't work :( how to handle it? please explain me cool way


Solution

  • First, std::function is:

    template< class >
    class function; /* undefined */
    template< class R, class... Args >
    class function<R(Args...)>;
    

    Your std::function<world&,void()> doesn't make sense. You are supposed to pick the function type you want to store in the function object.

    Next, you need a world to call one of its non-static member functions.

    What you can do is the following:

    #include <iostream>
    #include <functional>
    
    class world
    {
    public:
        void hello(){
            std::cout << "wow" << std::endl;
        }   
    };
    int main(void)
    {
        //std::function<world&,void()> pFn = &world::hello; //is this right???    
        world w;
        std::function<void()> pFn = [&w](){ w.hello();};
        pFn();
    }
    

    You need to make sure w is still alive when you call pFn(). Alternatively you could make pFn take a world as parameter, in either case you need an instance to call a non-static member function.

    PS: Note that in the above example there is really no point in using the std::function when you can use the lambda itself. std::function comes for a price that often you do not need to pay.