Reputation: 369
I would like to pass to a function a reference to a class method.
For example:
#include <functional>
struct Foo
{
int f(const int& val) const
{
return val+2;
}
};
int caller(const std::function<int(const int&)>& f)
{
return f(1);
}
int main()
{
caller([](const int& val){return val+2;}); // OK
Foo foo;
caller(foo.f); // WRONG
return 0;
}
How can I fix the second call of caller() (NB: Foo:f() is not static)?
Upvotes: 2
Views: 3182
Reputation: 290
In your case, function f
doesn't use any member of Foo
so it can be declared static
static int f(const int& val)
and passed as:
caller(&Foo::f);
But suppose that f
cannot be declared static
and you want to pass "reference" to member function of particular object.
You can use lambda in that case:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo
object is captured in square brackets (in this case by reference) so that you can call f
member function on that particular object.
Although it is not part of your question, I should add that it is not really useful to pass int
by const reference, as you will not gain any performance improvement that way. Actually, your code will run slower than if you pass int
by value.
Upvotes: 2