C++:将函数赋值给tr1 :: function对象

Sys*_*Lol 2 c++ delegates tr1

我们的一个类提供了tr1 :: function回调对象.但是,当我尝试为其分配成员函数时,我收到编译器错误.

以下示例未经测试,仅用于说明:

foo.h中:

class Foo()
{
public:
  Foo();
  std::tr1::function<void (int x)> F;
}
Run Code Online (Sandbox Code Playgroud)

Bar.h:

class Bar()
{
public:
   Bar();
   Foo* foo;
   void HookUpToFoo();
   void Respond(int x);
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

我们得到的编译器错误是指xrefwrap中的一行,是错误1错误C2296:'.*':非法,左操作数的类型为'int'C:\ Program Files\Microsoft Visual Studio 9.0\VC\include\xrefwrap 64

..在分配代表时我做错了什么?我想走更现代的路线并使用tr1 :: function而不是函数指针.

int*_*jay 5

成员函数接受另一个隐藏参数:this.这使它与function只接受一个参数的对象不兼容.你可以绑定一个成员函数使用特定的情况下bind,它也可在tr1:

using namespace std::tr1::placeholders;

this->foo->F = std::tr1::bind(&Bar::Respond, this, _1);
Run Code Online (Sandbox Code Playgroud)

这确保Bar::Respond将使用绑定的正确值调用this.它_1是附加参数(x)的占位符.

  • 或者只是`std :: tr1 :: bind(&Bar :: Respond,this)`,没有占位符. (4认同)