Function References

后端 未结 5 1381
醉话见心
醉话见心 2020-11-29 01:02

So I was just working with function pointers and I remembered that you could do this:

void Foo()
{
}

int main()
{
    void(& func)() = Foo;

    func();         


        
5条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:43

    in addition to the use as strategy (as pointed out by Robert Gould), I freqently use them at the entrance point to (template) metaprogramming. A function reference can easily be picked up by a template parameter; from this point on it can be passed through several layers of (metaprogramming) templates. Of course, this holds true for a function pointer as well, but the reference is an alias and thus communicates the intention more clearly.

    To give an example: when writing a generic command dispatching system for an application, a lot of different operations need to be announced as commands. We can use a simple "builder function" as front-end for the client code. Behind the scenes, this builder function picks up the actual function signature as template parameter, derives (by template metaprogramming) the actual parameter and return type values and possibly picks the suitable specialisation to store a "memento" and an "undo functor". These functors can than be stored either as function pointers internally, or using boost or tr1 or C++11 function objects. This way, it is possible to build a type safe command invocation and "undo" system.

提交回复
热议问题