Haggai Magen
Haggai Magen

Reputation: 103

Passing a class method as function argument

I am trying to send a method of a specific class instance as an argument to a function (foo), although I keep getting this error

invalid use of non-static member function...

(from the line foo(a->bar))

I'm not sure why do I get this error? Is there a possible work-around for it?

#include <iostream>
#include <functional>

void foo(std::function<void(void)> _func)
{
    _func();
}

class A
{
public:
    A()
    {
        x = 5;
    }
    void bar()
    {
        std::cout << x << std::endl;
    }

private:
    int x;
};

int main() {
    A a;
    foo(a->bar);
    return 0;
}

Upvotes: 1

Views: 146

Answers (2)

jonas_toth
jonas_toth

Reputation: 872

Your method isn't compatible to std::function, even it looks like. Every method has an implicit first argument, this.

So your signature looks like this

void bar(A* this) { /* ... */ }

This is not the case for static methods. These are like functions within the namespace of the class and

static void bar() { /* ... */ } 

Will saturate std::function.

Still, using a lambda (c++11) is most likely the better way for ur example.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

You have two options:

  1. Use std::bind: foo(std::bind(&A::bar, a)):

  2. Use lambdas: foo([&a]() { a.bar(); });

Upvotes: 5

Related Questions