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.
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
).