I’ve noticed the following code in several places in Unreal where it is possible to send in an address of a function to be called by using the & symbol and passing the function name. It also exists on timers. This is really cool and I have thought of a use for it in my own programs…Having looked around for an explanation of this, I find some vague info but not really what Im looking for. Can someone explain this (what is this technique known as) and point me in the direction of a tutorial that shows how to set this up in the function signature.
The literal name for the thing you’re talking about is simply “function pointer” (or sometimes, “pointer to function”)
Note that this is different from “pointer to member function”! Pointer to member function uses slightly more arcane syntax, and needs to be invoked on an object instance of the right class.
Finally, much C++ code these days use some kind of templated wrapper on top of “anything you can call” to hide these differences – you’ll instead pass in a std::function<> or similar, that is constructed based on the specifics of what it is you want to call, and it gets invoked using the operator() overload on the function template instance. (Which is a totally different thing from a “template function instance!” Words are hard!) The drawback with this is that the function that takes the function object as an argument, in turn needs to be templated. Unreal engine prefers not to use that kind of code style, because it generally generates bigger executables and pushes more logic to header files which in turn causes (even) longer compile times.
Of course this is true, but using templates (like <algorithm> from stl) gives the advantage that the passed lambda/function object can be inlined by compiler. Inlining gives massive boost in runtime and for me this is worth longer compilation times
In the case of using a traditional function pointer, I have doubts whether inlining is possible at all, and if so, probably under very restrictive conditions.
As always, everything depends on what’s your goal.
Thanks all, this is really cool, found some youtube videos now I know what I was looking for and I have it down!
…
//functions…
…
std::vector<int> values = {1,2,3,4,5};
PrintVector(values, &PrintValues);
PrintVector(values, &DoubleValues);
I like the unreal style, easy to read and to the point. Not liking templates as its a bit over me at the moment.
So cool, I wish I knew that a month ago when I wrote a horrible piece of code to call a different function after an arbitrary timer delay. It really was nasty although it worked fine!, and I could have used this. I will be from now!