[英]C++ std::function bind from derived class
If I had a base class MessageWrapper, with a child class SetConfigurationData, why does binding with a child class parameter not work? 如果我有一个基类MessageWrapper,带有子类SetConfigurationData,为什么绑定子类参数不起作用?
Shouldn't it work polymorphically? 不应该多态地工作吗?
Class MessageHandler
{
public:
void RegisterHandler(std::function<void(MessageWrapper &)> callback_)
{}
};
class Testing
{
public:
Testing(MessageHandler &handler_)
: m_Handler(handler_)
{
m_Handler.RegisterHandler(std::bind(&Testing::TestMessageHandler, this, std::placeholders::_1));
}
void TestMessageHandler(SetConfigurationData &msg_)
{}
MessageHandler m_Handler;
};
I get the error: "Failed to specialize function template 'unkown-type std::invoke( Callable &&, Types &&..)' 我收到错误:“无法专门化函数模板'unkown-type std :: invoke( Callable &&,Types && ..)'
It works if I do this: 如果我这样做,它的工作原理:
void TestMessageHandler(MessageWrapper &msg_)
{}
Polymorphism cannot work like this. 多态性不能像这样工作。 I will explain with an example. 我将用一个例子来解释。 Let's say the function. 让我们说这个功能。
void TestMessageHandler(SetConfigurationData &msg_)
has something specific to the child object in it's body. 在它的身体中具有特定于子对象的东西。 Say 说
msg.child_method()
Now since RegisterHandler callback_() takes base class as argument, what should it do with this "msg.child_method()" call since it's not a base class method ? 现在,由于RegisterHandler的callback_()将基类作为参数,因此它应该对这个“msg.child_method()”调用做什么,因为它不是基类方法?
Now, what happens if we do it the other way round. 现在,如果我们反过来这样做会发生什么。 The following works. 以下作品。
class MessageWrapper
{
};
class SetConfigurationData : public MessageWrapper
{
public:
void RegisterHandler(std::function<void(SetConfigurationData&)> callback_)
{}
};
class MessageHandler
{
};
class Testing
{
public:
Testing(SetConfigurationData &handler_)
: m_Handler(handler_)
{
m_Handler.RegisterHandler(std::bind(&Testing::TestMessageHandler, this, std::placeholders::_1));
}
void TestMessageHandler(MessageWrapper &msg_)
{}
SetConfigurationData m_Handler;
};
Even though TestMessageHandler takes MessageWrapper as argument, u can bind it to callback_ which takes Child class (SetConfigurationData) as argument. 尽管TestMessageHandler将MessageWrapper作为参数,但是您可以将它绑定到callback_,它将Child类(SetConfigurationData)作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.