1

how to make tail recursion optimization enabled, when function more and vals call each other?

now, when I set n = 5, but when I set n = 50000000, it will occur error.

using Cb = std::function<void(bool, int)>;
using Read = std::function<void(bool, Cb)>;
using Sink = std::function<void(Read&)>;
using Through = std::function<Read(Read&)>;

int main() {
    int n = 5;

    Read vals = [&](bool abort, Cb cb) {
        if (n-- <= 0) {
            return;
        }
        cb(false, n); // call `more` function
    };

    Sink logInt = [&](Read &read) {
        Cb more;
        more = [&](bool abort, int val) {
            cout << val << endl;
            read(false, more); // call `vals` function
        };

        read(false, more);
    };

    logInt(vals);


    return 0;
}

whole real code example

langyu
  • 68
  • 1
  • 7
  • 3
    You can't force it any any sort of portable way. Some compilers do it but it's not required. You'll have to switch to a non-recursive solution. – gct Jan 29 '20 at 15:07
  • I doubt your going to be able to using `std::function`s. `std::function` uses type erasure to store it's callable and that removes basically all the information the compiler needs to be able to try and optimize. – NathanOliver Jan 29 '20 at 15:08
  • gcc does it via `-foptimize-sibling-calls` which is enabled at `-O2`, `-O3`, and `-Os` – gct Jan 29 '20 at 15:10
  • 1
    in general `std::function` is to store all kinds of callables. When you need to store only a single object of some type, you don't need the power of `std::function`. Turning your lambdas into `std::function`s has downsides and no obvious advantage – 463035818_is_not_an_ai Jan 29 '20 at 15:10
  • 2
    You could always change your coding style to not cause a stack overflow and just loop around logInt while val's is giving you data – UKMonkey Jan 29 '20 at 15:11
  • there is one thing I dont know how to do with lambda only, and that is calling `more` recursively, unfortunately this recursion is the whole point of the question ;) – 463035818_is_not_an_ai Jan 29 '20 at 15:38
  • @formerlyknownas_463035818: There is a [standard trick](https://stackoverflow.com/a/18085333/8586227) for writing recursive lambdas (in C++14). – Davis Herring Jan 30 '20 at 03:46

0 Answers0