I don’t know why I’m having trouble finding this. I’m coming from a Swift/Kotlin worlds, where things like delegation and llambda functions are ‘easy’. I’ve implemented something similar in C, but in C everything is “flat” and I can define callbacks just as basic address pointers.
here is what I want to do, extrapolating it as high level as possible.
There is an app. it talks to a class, let’s call it “Dad”. Dad has a child class, called “Child”. This class has the name of the child, and randomly generates an integer ad some random time that “Dad” sees as a callback. “Dad” needs to send this callback to the app. So “Child” has one callback with an integer, and “Dad” then has one callback where it returns an integer, with the name of the child who generated it.
So, the app doesn’t know how many kids there are and doesn’t care. “Child” doesn’t know about the class called “Dad” (there may be another instance where the class is Mom or GrandDad or whatever, so it can’t care. The point is the Child doesn’t know the “type” of where it’s callback is going.
for the life of me, I can’t figure out how to make the callbacks work. I’ve seen examples of callbacks, but they usually have no parameters, or they involve static objects (no go), or they require the one doing the callback to know the class type of the one instantiating it (no go).
I’ve seen template functions, but this doesn’t seem to work right for me or I’m too stupid to understand it.
In C, I’d just use function pointers, but I’d have to have some other struct containing all the kids names and some parameter for how/when to do a “random” generation of a “random” number.
But it’s basically main registers a method to a callback from Dad which has two parameters (name of child, integer value), and Dad instantiates “N” children, registering a callback function from each child.
The fact that each child is the same is not something I want to have “fixed”. I could have “Son” and “Daughter”, and “Pet” – none of which are necessarily the same base class with different attributes – they could be completely independent.