Stateful Lambdas (Jason Turner)

I just watched Jason Turner’s latest C++ Weekly video, where he uses C++14 generalised lambda capture to implement the fibonacci sequence:


This is very cool – I hadn’t seen Fibonacci done this way before. I was interested in std::exchange too, introduced in C++14. As used here, std::exchange replaces the existing value of j with a new value and returns the original value, which is assigned to i. So this idiom allows you to update a value and store the previous value, all in a single expression.

Even better, Jason shows that this whole program is calculated at compile time in Clang – very impressive.

Leave a comment

Filed under C++

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.