C++ function returning function

后端 未结 7 571
南笙
南笙 2020-12-24 12:13

Where in the standard are functions returning functions disallowed? I understand they are conceptually ridiculous, but it seems to me that the grammar would allow them. Acco

相关标签:
7条回答
  • 2020-12-24 12:41

    Actually in C one cannot pass or return function. Only a pointer/address of the function can be passed/returned, which conceptually is pretty close. To be honest, thanks to possiblity of ommiting & and * with function pointers one shouldn't really care if function or pointer is passed (unless it contains any static data). Here is simple function pointer declaration:

    void (*foo)();
    

    foo is pointer to function returning void and taking no arguments.

    In C++ it is not that much different. One can still use C-style function pointers or new useful std::function object for all callable creations. C++ also adds lambda expressions which are inline functions which work somehow similar to closures in functional languages. It allows you not to make all passed functions global.

    And finally - returning function pointer or std::function may seem ridiculous, but it really is not. For example, the state machine pattern is (in most cases) based on returning pointer to function handling next state or callable next state object.

    0 讨论(0)
提交回复
热议问题