C++17 In Detail

22 June 2020

The C++ Lambda Story Book

Lambda Expressions appeared in C++11, and since then they become one of the most distinguishing features of Modern C++. What’s more, with each revision of the Standard the ISO Committee improved the syntax and capabilities of lambdas, so they are even more comfortable to use.

Read on to see how you can learn all the details of this powerful modern C++ feature.

A Few Questions to you?

  • Do you know all of the details of this feature?
  • Why we needed lambdas in the first place?
  • How the compiler “expands” the code for lambdas?
  • How to capture variables and even declare new captured elements?
  • And many more questions!

On my website, you can read at least five large articles that describe all the essential parts of lambdas:

Have a look if you haven’t read it before:

Would you like to see more?

Lambda Ebook

I packed my knowledge about lambdas into a beautiful ebook, with lots of examples and additional descriptions.
And just as with my book about C++17, I made it available at Leanpub.
The platform makes it easy for me to publish new updates, and everyone who has the book can immediately access the latest changes (at no charge).
Also, the platform allows you not only to read it as PDF but also Epub, Mobi or Online.

Here’s the list of the things you can learn:

  • C++03 - What was the motivation for the new C++ feature?
  • C++11 - Early days: You’ll learn about all the essential aspects of lambdas and several tricks you might apply. This is the longest chapter as we need to cover a lot of topics.
  • C++14 - Updates: See how to use generic lambdas and captures with an initialiser.
  • C++17 - More improvements, especially by handling this pointer and allowing constexpr. You’ll also learn how to leverage the overloaded pattern.
  • C++20 - In this chapter, you’ll see all of the new features adopted for C++20 like template lambdas and how to use them with concepts and constexpr algorithms.
C++ Lambda Story@Leanpub

Recent Changes

Here are the recent changes from April, May and June:

  • I rewrote the C++03 chapter and include sections about bind1st and bind2nd and other functional stuff - they are deprecated and then removed in C++17. There’s also another section in the C++14 chapter on how to replace that old functionality with modern alternatives.
  • I rewrote the C++20 chapter, as the C++20 Standard is mostly done and we won’t see any feature changes. This covers constexpr algorithms, template lambdas and a few other improvements.
  • New sections about deriving from lambda expressions. That includes the underlying theory, and then you’ll decipher the overloaded pattern that is handy for std::variant visitation. You also see a shorter syntax for C++20.
  • IIFE sections improved with one more example
  • Return type sections in C++11 chapter got an extra example
  • An updated book cover!
  • New appendices: the first one with a list of lambda “techniques” and then a second with top 5 lambda features (converted and adapted from my recent article)
  • Plus many updates across the whole book

You can download the sample (it’s almost half of the book!) from this page: C++ Lambda Story @Leanpub

Let’s now focus on two examples that I recently added to the book:

Example 1 - Lambdas And Concepts, C++20:

As you might already know, in C++20, we’ll get concepts… and they work nicely with lambdas, have a look:

Let’s define a concept for our IRanderable static interface:

template <typename T>
concept IRenderable = requires(T v) {
    {v.render()} -> std::same_as<void>;
    {v.getVertCount()} -> std::convertible_to<size_t>;
};

In the above example we define a concept that matches all types with render() and getVertCount() member functions. We can then use it to write a generic lambda:

#include <concepts>
#include <iostream>

struct Circle {
    void render() { std::cout << "drawing circle\n"; }
    size_t getVertCount() const { return 10; };
};

struct Square {
    void render() { std::cout << "drawing square\n"; }
    size_t getVertCount() const { return 4; };
};

int main() {
    auto RenderCaller = [](IRenderable auto &obj) {
        obj.render();
    };
    Circle c;
    RenderCaller(c);
    Square s;
    RenderCaller(s);
}

Play with the code @Wandbox

Thanks to the constrained auto we can define a generic lambda that is constrained with the given concept:

auto RenderCaller = [](IRenderable auto &obj) { }

Additionally, if you need more control over the template parameter, you can also use template lambdas!

auto foo = []<typename T>(std::vector<T> const& vec) { 
        std::cout<< std::size(vec) << '\n';
        std::cout<< vec.capacity() << '\n';
    };

This time you can add “template head” to the lambda.

Example 2 - Almost Always Auto and IIFE?

When the initialisation of a variable is complicated, and you’d like to make the variable const you can use the IIFE trick (Immediately Invoked Functional Expression) :

For example:

const auto EnableErrorReporting = [&]() { 
    if (HighLevelWarningEnabled())
        return true;

    if (HighLevelWarningEnabled())
        return UsersWantReporting();

    return false;
}();

if (EnableErrorReporting) {
    // ...
};

But… isn’t it hard to read?

Not only you need to decipher the type of EnableErrorReporting, but also you have to be careful and notice that we call lambda in the last line }();.

In the book, I’m showing at least two ways on how to improve the syntax and make it more readable. (hint: maybe we shouldn’t use auto here, and another option is to leverage std::invoke()).

The Plans

There will be one more update, planned near the end of summer. To make it visible and clear for the readers, I set the “progress” to 95% for the book.

The target is to reach 100+ pages and also release it at Kindle Direct Publishing store.

Your Feedback

I appreciate your initial feedback and support! The book has now more
than 800 readers (and only one refund)! That’s not too bad I think :)

Add your feedback/review here:
https://www.goodreads.com/book/show/53609731-c-lambda-story

You can use this comment site:
https://leanpub.com/cpplambda/feedback

Or just write a direct email to me:
bartlomiej DOT filipek AT bfilipek DOT com

How to Get the Book?

There are three ways:

If you like my work and you want to get extra C++ content, exlusive articles and weekly curated news, then check out my Patreon website:

© 2017, Bartlomiej Filipek, Blogger platform
Disclaimer: Any opinions expressed herein are in no way representative of those of my employers. All data and information provided on this site is for informational purposes only. I try to write complete and accurate articles, but the web-site will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use.
This site contains ads or referral links, which provide me with a commission. Thank you for your understanding.