Function returning another function

134 Views Asked by At

The question may be sounded quite silly, but why can't we do so? I mean, a declarator like the following:

void (foo())();

I've read the section 8.3.5 of the current C++ standard and didn't find how it implies from what said there.

Here is what the standard said about that:

In a declaration T D where D has the form

D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
ref-qualifieropt exception-specificationopt attribute-specifier-seqopt

and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list function of (parameter-declaration-clause ) cv-qualifierseqopt ref-qualifieropt returning T”.

So, formally, from that definition implies that my declration is a valid function declration. T D1, in my case has the form void foo() which is a perfectly valid declration. What did I miss?

2

There are 2 best solutions below

0
On BEST ANSWER

I've read the section 8.3.5 of the current C++ standard

Obviously not very carefully. §8.3.5 [dcl.fct]/p8:

Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.

2
On

I think it's because you can't create a temporary object of a function. However if you're planning to do something like this try returning a pointer to a function. Try this:

int (*fun())();

Pointer values can be returned by a function. You can't return a function because there is no function type.