I can easily bind member functions to a std::function
by wrapping them with a lambda expression with capture clause.
class Class
{
Class()
{
Register([=](int n){ Function(n); });
}
void Register(std::function<void(int)> Callback)
{
}
void Function(int Number)
{
}
};
But I want to bind them directly, something like the following.
// ...
Register(&Class::Function);
// ...
I think according to the C++11 standard, this should be supported. However, in Visual Studio 11 I get these compiler errors.
error C2440: 'newline' : cannot convert from 'int' to 'Class *'
error C2647: '.*' : cannot dereference a 'void (__thiscall Class::* )(int)' on a 'int'
With
std::function
andstd::bind
, you can treat different class member function the same.You can use
std::bind
: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 matchvoid(int)
. Hence the need forstd::bind
:For example
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:then
According to Stephan T. Lavavej - "Avoid using bind(), ..., use lambdas". https://www.youtube.com/watch?v=zt7ThwVfap0&t=32m20s
In this case: