English 中文(简体)
C++: 职能分配到:功能物体
原标题:C++: Assigning a function to a tr1::function object

One of our classes provides tr1::function callback object. When I try assigning a member function to it, though, I get a compiler error.

以下例子未经测试,只是为了说明:

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 FilesMicrosoft Visual Studio 9.0VCincludexrefwrap 64

。 在指派代表方面,我做了哪些错误? 我想走更现代的道路,使用:功能而不是功能点。

最佳回答

成员的职能是接受另一个隐藏的参数:this。 这使得它不符合您的<代码>功能<>/代码>只接受一个参数的物体。 可通过<代码>bind对成员职能加以约束。

using namespace std::tr1::placeholders;

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

这确保了<条码>Bar:Respond的正确价值被称作<条码>。 <代码>1为附加参数的持有人()。

问题回答

<代码>Bar:Respond为成员职能,而不是职能。 无需<条码>。 这与“避免使用<代码>(Bar:*)(int) 成员职能联络点和 避免(*)(int)职能点之间的区别相同。

页: 1 成员职务的反对。

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




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签