Function References

后端 未结 5 1398
醉话见心
醉话见心 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:37

    I think your example usage is quite good. Because if you would use an ordinary function pointer, and you then apply the address-of operator, you would get the address of the function pointer. Using a reference to function will do the expected thing, in that it returns a pointer to the function itself.

    I also can't think of many examples. Keeping function references, as you point out, has some ugly consequences. Another possibly unwanted consequence is, if kept as a class-member, your objects will be non-assignable if you don't write your own operator= and refrain from trying to re-assign the function-reference.

    I think most uses of function references are implicit, much like most uses of array-references - although much more so, when you accept arguments by-reference:

    template
    void do_something(T const& t) { ... }
    

    While accepting arrays by reference has the advantage of not losing their size information, accepting functions by reference explicitly doesn't seem to have an advantage (at least as far as I can see). I suppose the existence of function references largely is justified by the idealistic view of a reference as an alias-name of some object or function, together with the fact that it allows passing functions to such templates that accept their argument by reference.

    I would probably avoid using them if I wouldn't need them inevitably. Constant function pointers also provide non-reassignable callables, and will probably avoid confusions when other programmers, who possibly are not very familiar with this language niches, read your code. Worth to note that Vandervoorde & Josuttis also recommend to avoid them to reduce confusion (in their book C++ Templates - The Complete Guide).

提交回复
热议问题