std::function to member function
#include <functional>
struct A
{
int func(int x, int y)
{
return x+y;
}
};
int main()
{
typedef std::function<int(int, int) > Funcp;
A a;
//Funcp func = std:::bind(&A::func, &a);
Funcp func = std::bind(&A::func, a, std::placeholders::_1);
return 0;
}
I am getting errors in both of t开发者_高级运维he above bind functions:
error C2825: '_Fty': must be a class or namespace when followed by '::'
Where is the syntax error? I am using visual studio 2010
Funcp func =
std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);
It took a while for me to figure out what's happening. So adding it here for the benefit of others, where an explanation would help. I've renamed some functions and variables for more clarity.
#include <functional>
struct A
{
int MemberFunc(int x, int y)
{
return x+y;
}
};
int main()
{
typedef std::function<int(int, int)> OrdinaryFunc;
A a;
OrdinaryFunc ofunc = std::bind(&A::MemberFunc, a, std::placeholders::_1, std::placeholders::_2);
int z = ofunc(10, 20); // Invoke like an ordinary function
return 0;
}
Class member functions have an implicit/hidden parameter which points to the object (this
pointer). These member functions can be invoked only by providing an object, which makes it different from an ordinary function.
std::bind
can be used to "convert" a member function into an ordinary function by passing the object (pointer or reference). It has be the first argument in the list of args
(&a
or a
in this case) following the member function. In the new function, the object is bound to the implicit/hidden parameter of the member function, and need not be passed when invoked. The unbound arguments are represented by the placeholders _1
, _2
and have to be passed when invoked.
精彩评论