Callback: function pointer as argument and passing an aditional agrument

714 Views Asked by At

How to pass a function pointer as argument with an argument?

void A(){
    std::cout << "hello" << endl;
}

void B(void (*ptr)()){ // function pointer as agrument
    ptr(); // call back function "ptr" points.
}

void C(string name){
    std::cout << "hello" << name << endl;
}

void D(void (*ptr2)(string name)){ // function pointer as agrument
    ptr2(name); // error 1
}

int main(){
    void (*p)() = A; // all good
    B(p); // is callback // all good

    void (*q)(string name) = C;
    D(q)("John Doe"); // error 2
    return 0;
};

errors:
1 - use of undeclared identifier 'name'
2 - called object type 'void' is not a function or function pointer

2

There are 2 best solutions below

0
On BEST ANSWER

You should make D taking two parameters, one for the function pointer, one for the argument to be passed to function pointer. E.g.

void D(void (*ptr2)(string), const string& name){
    ptr2(name);
}

then call it like

D(q, "John Doe");
1
On
  1. name is a part of type declaration for ptr2 and is not a variable in D.
  2. Tou are trying to call what is returned from D, which is void. , is used to separate arguments in C++.

Try this:

#include <iostream>
#include <string>
using std::endl;
using std::string;

void A(){
    std::cout << "hello" << endl;
}

void B(void (*ptr)()){ // function pointer as agrument
    ptr(); // call back function "ptr" points.
}

void C(string name){
    std::cout << "hello" << name << endl;
}

void D(void (*ptr2)(string name), string name){ // function pointer and a string as agrument
    ptr2(name);
}

int main(){
    void (*p)() = A; // all good
    B(p); // is callback // all good

    void (*q)(string name) = C;
    D(q, "John Doe"); // pass 2 arguments
    return 0;
} // you don't need ; here