将可调用对象传递给成员函数
class Action {
public:
void operator() () const;
}
class Data {
public:
Data();
~Data();
Register(Action action) { _a = action; }
private:
Action _a;
}
class Display {
public:
Display(Data d) { d.Register( bind(Display::SomeTask, this, _1) ); }
~Display();
void SomeTask();
}
我想将 Data 的私有成员 _a 绑定到 Display 的成员函数,但是当我调用 d.Register 时,出现编译错误,提示我的参数类型不匹配,我做错了什么? 谢谢。
class Action {
public:
void operator() () const;
}
class Data {
public:
Data();
~Data();
Register(Action action) { _a = action; }
private:
Action _a;
}
class Display {
public:
Display(Data d) { d.Register( bind(Display::SomeTask, this, _1) ); }
~Display();
void SomeTask();
}
I want to bind the private member _a of Data to a member function of Display, but I get compile errors saying my argument types don't match when I call d.Register, what am I doing wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要做什么并不完全清楚,但我假设“bind”是 boost::bind (或 tr1::bind)。
bind(Display::SomeTask, this, _1) 的几个问题:
使用 Boost.Function 和 Boost.Bind,您可以编写以下内容来实现我猜您想要做的事情:
What you're trying to do is not completely clear, but I'll assume that "bind" is boost::bind (or tr1::bind).
A couple of problems with bind(Display::SomeTask, this, _1):
Using Boost.Function and Boost.Bind, here's what you could write to acheive what I guess you're trying to do:
我看不到“bind”返回什么,但我绝对确定这与 Action 类不兼容。 另外,您正在使用“复制语义”,因此如果 Action 具有空实现,您将永远不会得到想要的。
尝试更改 Register(Action* action),并允许“绑定”返回 Action 类的某些子级。
还要检查迁移到模板的可能性 - 甚至可以完全排除 Action 类
在这种情况下,您可以将具有重写的operator() 的类用作不带参数的函数。
I cannot see what 'bind' returns, but I absolutely sure this is not compatible with Action class. Also you are using 'copy semantic', so if Action has empty implmentation, you will never get desired.
Try change Register(Action* action), and allow 'bind' to return some child of Action class.
Also review possibility to migrate to templates - than you even can exclude Action class at all
In this case you could be able to use as classes with overridden operator() as functions without argument.
首先,你必须使用
&Display::SomeTask
并给Register
一个返回类型,然后根据你的需要SomeTask*this
上的 code>:省略_1
。Display
对象上调用SomeTask
:用 Shift_1
代替this
。然后,boost::bind 返回一些复杂的合成类型,它将调用指定的函数。 您需要一种存储它的方法,这就是
boost::function
派上用场的地方。 这就是你可以做到的然后它应该可以工作。
First, you have to use
&Display::SomeTask
and giveRegister
a return type, and then it depends on your needsSomeTask
on*this
: Omit_1
.SomeTask
on a passedDisplay
object: Shift_1
in place ofthis
.Then,
boost::bind
returns some complicated synthesized type that will call the specified function. You need a way to store it, which is whereboost::function
comes handy. This is how you can do itThen it should work.