【问题标题】:C++: Assigning a function to a tr1::function objectC++:将函数分配给 tr1::function 对象
【发布时间】:2011-11-03 17:30:49
【问题描述】:

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

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

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
}

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

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

【问题讨论】:

    标签: c++ delegates tr1


    【解决方案1】:

    成员函数接受一个额外的隐藏参数:this。这使其与您的 function 对象不兼容,该对象只接受一个参数。您可以使用bind 将成员函数绑定到特定实例,tr1 也提供此功能:

    using namespace std::tr1::placeholders;
    
    this->foo->F = std::tr1::bind(&Bar::Respond, this, _1);
    

    这可确保调用Bar::Respond 时将正确的值绑定到this_1 是附加参数 (x) 的占位符。

    【讨论】:

    • 或者只是std::tr1::bind(&amp;Bar::Respond, this),不带占位符。
    • @Alexandre:没有占位符对我不起作用:ideone.com/k3VD9
    • 谢谢,interjay,当我使用绑定而不是使用 = 赋值时,它可以工作。注意:我还必须使用占位符,否则无法编译。
    【解决方案2】:

    Bar::Respond 是成员函数,而不是函数。没有this 就不能调用它。这和void (Bar::*)(int)成员函数指针和void (*)(int)函数指针的区别是一样的。

    您可以使用mem_fn 从成员函数创建function 对象。

    F = std::bind1st(std::tr1::mem_fn(&Bar::Respond), this);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多