0

So I am trying to solve this question where I would have to write a small library that executes a callback function in C++. The detailed question is:

Write a small library which allows:

  1. Registering callbacks for future one time execution by specifying a function, an optional argument and time in seconds (relative to now) that specifies when the callback should be run.
  2. An execute function which should execute (call) all due callbacks?

I understand what a callback function is and why it is used as callbacks are normally passed into a function and provides the developer with the flexibility to change the callback code without having to modify the calling function. But in this case I am just not understanding the goal of this question number 1.

My Doubts

So does question 1 mean that the function that is going to call the callback function should call it after some seconds? What is the callback function executing inside of it? For e.g I am guessing that the callback function does not take any arguments and will just execute some task.

The function that is calling the callback function inside of it takes two arguments: an optional argument and time in seconds (relative to now) that specifies when the callback should be run.

This is supposed to be a full program i.e we have to write a int main() function as well. So I am guessing that inside the int main() function I would have to call the function with the delay and also pass in the callback function as an optional argument and that function will call the callback function after the specified delay inside of it?

Would you please explain in simpler terms how to go about writing this library in C++? Maybe a pseudocode will help me a lot as I am unsure of the structure of the entire program.

Ashish
  • 75
  • 1
  • 9
  • Do you understand #1? Or you don't understand both #1 and #2? – Louis Go Nov 29 '21 at 01:52
  • Search for "register callback" should give you some results for reference. Eg: [this](https://stackoverflow.com/q/18814157/4123703) – Louis Go Nov 29 '21 at 01:53
  • @LouisGo I do not understand #1 especially since it will have the definition of callback. – Ashish Nov 29 '21 at 01:54
  • Please [update] your question about what you don't understand or which description contradicts your understanding. For #1, it's like `register( callback ptr, callback arguments, time_t )`. – Louis Go Nov 29 '21 at 01:55
  • @LouisGo I have updated the question with my doubts. I hope it helps you to answer my doubts. Thank you – Ashish Nov 29 '21 at 02:09
  • Check [this answer](https://stackoverflow.com/a/14189561/4123703). For timed callback, try `std::async` with [this answer](https://stackoverflow.com/a/32645947/4123703) – Louis Go Nov 29 '21 at 02:27

0 Answers0