How to directly bind a member function to an std::function in Visual Studio 11?
I think according to the C++11 standard, this should be supported
Not really, because a non-static member function has an implicit first parameter of type (cv-qualified) YourType*
, so in this case it does not match void(int)
. Hence the need for std::bind
:
Register(std::bind(&Class::Function, PointerToSomeInstanceOfClass, _1));
For example
Class c;
using namespace std::placeholders; // for _1, _2 etc.
c.Register(std::bind(&Class::Function, &c, _1));
Edit You mention that this is to be called with the same Class
instance. In that case, you can use a simple non-member function:
void foo(int n)
{
theClassInstance.Function(n);
}
then
Class c;
c.Register(foo);
According to Stephan T. Lavavej - "Avoid using bind(), ..., use lambdas". https://www.youtube.com/watch?v=zt7ThwVfap0&t=32m20s
In this case:
Class()
{
Register([this](int n){ Function(n); });
}
You can use std::bind
:
using namespace std::placeholders; // For _1 in the bind call
// ...
Register(std::bind(&Class::Function, this, _1));