Mas Bagol
Mas Bagol

Reputation: 4617

Pass callback function with argument as parameter to other function

I have this:

// Call back function take string argument by ref.
typedef void (*Callback)(string&);

And I have this too:

// Function that take Callback as an argument
void need_a_callback (Callback func) {

    // Do something

}

The function that will be called back:

void modify(string& text) {

    text = "";

}

And now, how can I pass modify to need_a_callback?

Upvotes: 1

Views: 1567

Answers (1)

Bipi
Bipi

Reputation: 3579

Callbacks are function pointers. So you pass callbacks like pointers.

It results in this :

need_a_callback(modify);

Then, in need_a_callback(), you call your callback like this :

// Function that take Callback as an argument
void need_a_callback (Callback func) {

    String text = "my text";
    func(text);

}

Upvotes: 1

Related Questions