I have a tree-traversal API that looks like this
treeTraverse(Tree *ptr, (void *) call_back(Tree *ptr));
This API traverses the tree and calls the call back function with each entry. I want to traverse the tree and call a function
myFunc(Tree *ptr, int a, int b)
for every entry on the tree, but as you can see above the call back function only accepts one argument, so registering myFunc() as the call back function wont work. How do I get around this problem.
Rewriting the treeTraverse() API to accept variable arguments would not feasible, as it is a framework API and if I need to change it I would have to get it reviewed by lot of people. Not something I am looking forward to as I only need to implement a very small functionality.
Another way way would be to make the variables ‘a’ & ‘b’ global, so myFunc can access it. but this solution looks very ugly.
Is there any other way around this?
Making
aandbglobal seems like a reasonable solution, given your circumstances. Be careful, though, it isn’t thread or recursion safe.If you could add just a single extra argument to
treeTraversewhich gets passed to the callback, then you can pass an arbitrary number of extra arguments using a struct:This is a standard feature of most code that uses callbacks. You should insist that it get added to your framework API, it is a much better solution.