C ++:将函数分配给tr1 :: function对象 [英] C++: Assigning a function to a tr1::function object
问题描述
我们的一个类提供了tr1 :: function回调对象。
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
}
我们得到的编译器错误指的是xrefwrap中的一行,并且是
错误1错误C2296:'。*':illegal ,左操作数具有类型'int'C:\Program Files\Microsoft Visual Studio 9.0 \VC\include\xrefwrap 64
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
..我是什么在分配一个委托做错了?我想去更现代的路线,并使用tr1 ::函数,而不是函数指针。
..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.
推荐答案
隐藏参数: this
。这使得它与您只接受一个参数的函数
对象不兼容。您可以使用 tr1
:
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);
这将确保 Bar :: Respond
被正确的值绑定到 this
。 _1
是附加参数( x
)的占位符。
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
).
这篇关于C ++:将函数分配给tr1 :: function对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!