Previous Entry Share Next Entry
Explaining Language Design (Part 3: Lambdas in C++)

Countining with the presentation, "The Last Thing D Needs" goes into lambda expressions. C++ builds a lambda as an anonymous class. This is similar to the approach Java is using. I would describe a D lambda as a "uninstantiated anonymous template." The reason is because D can handle type deduction from lambda use.

#include <assert.h>

main(int arc, char** argv) {
    int cxprime = 1;
    auto lamPrime = [cxprime]() mutable {
        assert(cxprime == 1);
        cxprime = 10;
    assert(cxprime == 1);

This came as a surprise to me, so I thought summarizing the semantics of C++ lambdas was appropriate to teach those unfamiliar and as a refresher.

This simple program declares an integer with the value of 1. My lambda captures cxprime as demonstraited by the assertion, and assigns 10. After calling my new lambda, the cxprime integer remains the same value.

    auto lamPrime2 = [&]() mutable {
        assert(cxprime == 1);
        cxprime = 10;
    assert(cxprime == 10);

    return 0;

Fear not, C++ can create a proper closure; and as an added bonus the captures are infered! And if that is not enough feel free to choose from the other forms of lambdas. However this will be the semantics which we find in D.

Since today was taken up my learning C++, I'll be doing the D portion in Part 4.

  1. Part 1: Default Initialization
  2. Part 2: Const Inference
  3. Part 3: Lambdas in C++
  4. Part 4: Lambdas in D
  5. Part 5: Type Inference
  6. Part 6: Inheritance
  7. Part 7: Algorithm Complexity
  8. Part 8: Essential Complexity


Log in