Create a std::function object from a member function

Sometimes, you need to pass a member function as a std::function object. You can’t directly use the member function address. Instead you need to add ‘this’ or other instance with the address of its member function.

There are two ways to do it:

1) Using std::bind

for member functions without parameters, you can do this: (e.g. bool Foo::doSomething() )

std::function<bool(void)> f = std::bind(&Foo::doSomething, this);

for member functions with parameters, you can do this using std::placeholders: (e.g. bool Foo::doSomething(int, int, float) )

std::function<bool(int, int, float)> f = std::bind(&Foo::doSomething, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);

std::placeholders contains _1 to _10. It’s good for normal use.

2) Using Lambda expression

std::function<bool(int, int, float)> f = [&] (int a, int b, float c) ->bool {
  return this->doSomething(a, b, c);
};

[&] or [=] depends on your context.

Published by

vivo

This is Vivo. Yes, I'm Vivo.

Leave a Reply

Your email address will not be published. Required fields are marked *