1

I am trying to use an Arduino library and to use one of it's functions as a parameter in my own function, but I don't know how can I do that. I tried the code below but I get an error.

Any help will be appreciated.

P.S: I do not have an option to use auto keyword.

using namespace httpsserver;
HTTPServer Http;
typedef void (*Register)(HTTPNode*); // My typedef
Register Node = Http.registerNode;

When I am trying to call Node (...), I get the error below.

Cannot convert 'httpsserver::ResourceResolver::registerNode'
from type 'void (httpsserver::ResourceResolver::)(httpsserver::HTTPNode*)' 
to type 'Register {aka void (*)(httpsserver::HTTPNode*)}'

How can I create a function pointer for the type :

'void (httpsserver::ResourceResolver::)(httpsserver::HTTPNode*)'

I want to use it as a parameter in another function:

// My Declaration
void Get(void(*Register)(httpsserver::HTTPNode*), const std::string& path);

// Usage
Get (Http.registerNode(...), ""); // Like so

How can I do that?

1
  • In C++, there is a difference between a pointer to a function and a pointer to a memberfunction. They are incompatible, but there may be workarounds. These keywords should get you started though. Commented May 15, 2021 at 18:15

1 Answer 1

1

A member function pointer is not a function pointer.

typedef void (httpsserver::*Register)(HTTPNode*); // My typedef
Register Node = &httpsserver::registerNode;

usage:

void Get(void(httpsserver::*Register)(httpsserver::HTTPNode*), const std::string& path);
Get (&httpsserver::registerNode, "");

you have to pass the httpsserver::HTTPNode* into Register within Get.

If you want to bind the arguments to the function object and call it later, you want std::function<void()>:

void Get(std::function<void()>, const std::string& path);
Get ([&]{ Http.registerNode(...); }, "");

note, however, that this makes lifetime of the objects refered to within the {} above quite dangerous.

Sign up to request clarification or add additional context in comments.

1 Comment

typedef void (httpsserver::ResourceResolver::*Register)(httpsserver::HTTPNode*); Worked as expected. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.