Search code examples
c++function-pointerspointer-to-memberfunction-binding

Using pointers to member to pass member function as arguments


#include <iostream>
#include <functional>

class Foo 
{
    public:
    Foo(int value)
    : value_(value){}
    void print()
    {
        std::cout << "member print: " << value_ << std::endl;
    }
    int value_;
};

void print()
{
    std::cout << "stand alone print" << std::endl;
}

template<typename F>
void execute(F&& f)
{
    f();
}

int main()
{ 

    execute(print);

    Foo foo(5);

    auto binded = std::bind(&Foo::print,foo);
    execute(binded);

    //auto Foo::* foo_print = &Foo::print;
    //execute(foo.*foo_print);

}

The code above compiles and runs fine.

But if the last part, which uses the pointers to the print member function, is uncommented, then compilation fails with:

error: invalid use of non-static member function of type ‘void (Foo::)()’ 

Is there a syntax error in the code, or is this an impossibility for some reason?


Solution

  • You can't pass a non-static member function to execute, because it depends on the this element (and so it needs an invocation object), instead you can use a lambda:

    execute([&](){foo.print();});