问题
One of our classes provides tr1::function callback object. When I try assigning a member function to it, though, I get a compiler error.
The examples below are untested and just to illustrate:
Foo.h:
class Foo()
{
public:
Foo();
std::tr1::function<void (int x)> F;
}
Bar.h:
class Bar()
{
public:
Bar();
Foo* foo;
void HookUpToFoo();
void Respond(int x);
}
Bar.cpp:
Bar()
{
this->foo = new Foo();
this->HookUpToFoo();
}
void Bar::HookUpToFoo()
{
this->foo->F = &Bar::Respond; // error
}
void Bar::Respond(int x)
{
// do stuff
}
The compiler error we get refers to a line in xrefwrap and is Error 1 error C2296: '.*' : illegal, left operand has type 'int' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\xrefwrap 64
..What am I doing wrong in assigning a delegate? I want to go the more modern route and use tr1::function rather than function pointers.
回答1:
A member function accepts an additional hidden parameter: this. This makes it incompatible with your function object which only accepts one parameter. You can bind a member function to a particular instance using bind, which is also available in tr1:
using namespace std::tr1::placeholders;
this->foo->F = std::tr1::bind(&Bar::Respond, this, _1);
This ensures that Bar::Respond will be called with the correct value bound to this. The _1 is a placeholder for the additional parameter (x).
回答2:
Bar::Respond is a member function, not a function. It cannot be called without a this. This is the same as the difference between a void (Bar::*)(int) member function pointer and a void (*)(int) function pointer.
You can use mem_fn to create a function object from a member function.
F = std::bind1st(std::tr1::mem_fn(&Bar::Respond), this);
来源:https://stackoverflow.com/questions/7999304/c-assigning-a-function-to-a-tr1function-object