in my base class, this is a public non-static member function:
void BaseClass::SetPorcessMethod()
{
//do something
Listener.support(methods::POST, this->HandlePost);
//do something
}
In the function above, Listener
is a static member variable.
Function HandlePost
is a pure virtual function which is implemented by all derived classes. I want to use this
pointer to call different HandlePost
from different derived class.
Like:
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();
However, it displaysBaseClass::HandlePost:function call missing argument list use &BaseClass::HandlePost:function to create a pointer to member
.I know this is because 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
But what should I do so that I can call the function from derived class withsupport()
?
You are trying to pass a member function to support
. In order to call such a function the caller need the member function arguments and the pointer to the instance to call the function on.
However support
expects a std::function<void(http_request)>
, i.e. without the instance pointer. So you have to wrap the call into another callable which does not need to have the BaseClass
instance pointer passed. You can do that with a lambda (or std::bind
if you prefer):
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>
for the latter variant.