Not allowed to return a function from a function. How could I?

11,460

Solution 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.

Solution 2

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++.

Solution 3

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; };
}
Share:
11,460
Luchian Grigore
Author by

Luchian Grigore

Former Microsoft Visual-C++ MVP.

Updated on June 18, 2022

Comments

  • Luchian Grigore
    Luchian Grigore almost 2 years

    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
    }
    
  • Andy Prowl
    Andy Prowl about 11 years
    Technically, lambdas are not functions though, they are instances of functors
  • Lightness Races in Orbit
    Lightness Races in Orbit about 11 years
    +1: Exactly. Also, this is just one of those rare instances where C++ makes things clear and explicit for us rather than leaving us to derive it from the grammar and other various rules (such as non-copyability). Praise him!
  • Andy Prowl
    Andy Prowl about 11 years
    @LightnessRacesinOrbit: Indeed it is. I often feel like deducing a rule from the Standard is like proving a theorem of Number Theory. Not in this case.
  • Lightness Races in Orbit
    Lightness Races in Orbit about 11 years
    Yeah; it's interesting that it's rare enough to actually generate an SO question from an alarmed OP when it does happen.