Not allowed to return a function from a function.

2019-05-06 05:24发布

问题:

8.3.5/8 Functions [dcl.fct] says

[...] 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. [...]

Why so explicit of a rule? Is there some syntax that would even allow returning a function as opposed to a function pointer?

Am I miss-interpreting the quote?

typedef void (*fp)();

void foo(){}
fp goo()
{
    return foo; //automatically converted to function pointer
}

回答1:

This is quite a contrived 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.


回答2:

I know this probably does not answer your question completely but it does so partially

You can return a function from another function (that's what lambdas are)

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


回答3:

Is there some syntax that would even allow returning a function as opposed to a function pointer?

A syntax? Sure there is:

using fun = int (int);

fun function_that_returns_a_function();

That doesn’t compile because the rule in §8.3.5/8 forbids it. I don’t know why the rule specifically exists – but consider that the type “function” doesn’t have any size so you cannot create objects of function type in C++.