在我的基类中,这是一个公共的非静态成员函数:
void BaseClass::SetPorcessMethod()
{
//do something
Listener.support(methods::POST, this->HandlePost);
//do something
}
在上面的函数中,Listener
是一个静态成员变量。
函数HandlePost
是一个纯虚函数,由所有派生类实现。我想使用this
指针从不同的派生类中调用不同的HandlePost
。
像:
class BaseClass
{
public:
static http_listener listener;
void SetPorcessMethod();
virtual void HandlePost((http_request request) = 0;
/*listener is init in constructor , not display here*/
}
class Derived2:public BaseClass
{
void HandlePost(http_request request);
}
class Derived1:public BaseClass
{
void HandlePost(http_request request);
}
Derived1 instance1;
instance1.SetPorcessMethod();
Derived2 instance2;
instance2.SetPorcessMethod();
但是,它会显示BaseClass::HandlePost:function call missing argument list use &BaseClass::HandlePost:function to create a pointer to member
。我知道这是因为Your code attempts to pass a pointer-to-member-function, which cannot be converted to a pointer-to-function. This is because a pointer-to-member-function can only be called on an object, so it wouldn't know what object to use.
Function call missing argument list to create pointer
但是我该怎么办才能用support()
从派生类中调用函数?
答案 0 :(得分:2)
您正在尝试将成员函数传递给support
。为了调用这样的函数,调用者需要成员函数参数和指向实例的指针来调用函数。
但是support
需要std::function<void(http_request)>
,即没有实例指针。因此,您必须将调用包装到另一个不需要传递BaseClass
实例指针的callable中。您可以使用lambda(或std::bind
,如果您愿意):
Listener.support( methods::POST,
[this](http_request request){return HandlePost(request);} );
Listener.support( methods::POST,
std::bind(&BaseClass::HandlePost, this, std::placeholders::_1) );
对于后一种变体, #include<functional>
。