It is not allowed to return a function from a function. How could I?

8.3.5/8 Functions [dcl.fct] says

[...] Functions should not have a return type, type or function , although they may have a return type of a type pointer or a reference to such things. [...]

Why is there such a clear rule? Is there any syntax that would even allow the return of a function as opposed to a function pointer?

Am I missing a quote translation?

 typedef void (*fp)(); void foo(){} fp goo() { return foo; //automatically converted to function pointer } 
+4
source share
3 answers

This is a pretty far-fetched example of a function trying to return a function:

 void foo() { } template<typename T> T f() { return foo; } int main(){ f<decltype(foo)>(); } 

This is the error I get from Clang 3.2:

 Compilation finished with errors: source.cpp:7:5: error: no matching function for call to 'f' f<decltype(foo)>(); ^~~~~~~~~~~~~~~~ source.cpp:4:3: note: candidate template ignored: substitution failure [with T = void ()]: function cannot return function type 'void ()' T f() { return foo; } ~ ^ 1 error generated. 
+3
source

I know this probably doesn't fully answer your question, but in part it does

You can return a function from another function (what is lambda)

 std::function<int (int)> retLambda() { return [](int x) { return x; }; } 
+1
source

Is there any syntax that would even allow the return of a function as opposed to a function pointer?

Syntax? Of course have:

 using fun = int (int); fun function_that_returns_a_function(); 

This does not compile because the rule in ยง8.3.5 / 8 forbids it. I donโ€™t know why the rule specifically exists, but keep in mind that the type "function" has no size, so you cannot create objects of type functions in C ++.

+1
source

All Articles