Friday, 24 February 2017

Advanced Stateful Lambdas


Earlier this week I listened to Episode 51 of C++ Weekly Youtube "show" 😉 by @lefticus:
...and I just had to write this cool stuff down before I forget it!

So treat this post as a kind of engineering notebook - not my ideas, not my code, just a remainder and a reference. So without much ado, here's the code:
int main()
{
  auto fib = [a = 0, b = 0] () mutable {
    struct Results {
      int& a;
      int& b;

      Results next(int num = 1) {
        while (num > 0) {
          a = std::exchange(b, b + a);
          --num;
        }
        return *this;
      }
      
      operator int() {
        return a;
      }
    }

    return Results{a, b}.next();
  };

  // main
  return fib().next(5);

  // or:
  // return fib().next().next().next().next().next()

  // or:
  // return fib().next().a;
}
I won't comment on any part of the code, as not to take credit for work of others. If you want to know what this is about, just listen to this episode of C++ Weekly. Or even better, try to find it out by yourself and listen to it after that!

By the way, I support Jason on Patreon, and I think, you should support him too because of his fantastic job with C++ Weekly!

PS: here is another interesting code, this time  from episode 50, exploring generic lambdas and the "template if":
int intTotal = 0;
int doubleTotal = 0.0;
std::common_type<decltype(intTotal), decltype(doubleTotal)> grandTotal;

auto generic_visitor[&intTotal, &doubleTotal, &grandTotal] (const auto v) {
  grandTotal += v;

  if constexpr(std::is_same<double, decltype(v)>{} {
    doubleTotal += v;
  } else {
    intTotal += v;
  }
};

No comments: