Skip to main content

Fun with Lambdas: C++14 Style (part 2)


Look at some interesting examples of C++11/14 lambdas and how they interact with other language features and libraries. I hope to find some time to add some explanations. See part 1 if you missed it.

  • Associative containers and lambdas
    std::set<int, std::function<bool(int, int)>> 
      numbers([](int i, int j) { return i < j; });
    
  • Recursive Lambdas (see Creating recursive lambdas and returning them too!)
    auto make_fibo() 
    {
      return [](int n) {
        std::function<int(int)> recurse;
        recurse = [&](int n){ 
           return (n<=2)? 1 : recurse(n-1) + recurse(n-2); 
        }; 
        return recurse(n);
      };
    }
    
  • Composable list manipulation (e.g., cpplinq, narl, LEESA)
    Box boxes[] = { ... };
    int sum_of_weights = 
         cpplinq::from_array(boxes)
      >> where([](const Box & box) { 
           return box.color == Color.RED;
         })
      >> select([](const Box & box) {
           return box.get_weight();
         })
      >> sum();
    
    
  • Overloaded Lambdas
    template <class... F>
    struct overload : F... {
      overload(F... f) : F(f)... {}  
    };
    
    template <class... F>
    auto make_overload(F... f) {
      return overload<F...>(f...);   
    }
    
    auto f = 
        make_overload([](int i) { /* print */ },
                      [](double d) { /* print */ });
    f(10); // int 
    f(9.99); // double
    
  • Type Switch (simple pattern matching) (see type_switch.cpp and this paper)
    struct Base { 
      virtual ~Base() {} 
    };
    struct Derived : Base {};
    
    template <class Poly>
    void test(Poly& p) {  
      match(p)(
        [](int i)             { cout << "int";       },
        [](std::string &)     { cout << "string";    },
        [](Derived &)         { cout << "Derived";   },     
        [](Base &)            { cout << "Base";      },    
        otherwise([](auto x)  { cout << "Otherwise"; })
      );  
    }
    Derived d;
    Base &b = d;
    std::string cpptruths = "C++ Truths";
    boost::any something = cpptruths;
    
    test(10);        // int
    test(cpptruths); // string
    test(something); // string
    test(b);         // Derived
    test(9.99);      // Otherwise
    
  • Converting shared_ptr between boost and std (see StackOverflow)
    template <typename T>
    boost::shared_ptr<T> 
    make_shared_ptr(std::shared_ptr<T> ptr) 
    {      
      return boost::shared_ptr<T>(ptr.get(), 
        [ptr](T*) mutable { ptr.reset(); });
    }
    
    template <typename T>
    std::shared_ptr<T> 
    make_shared_ptr(boost::shared_ptr<T> ptr)
    {      
      return std::shared_ptr<T>(ptr.get(), 
        [ptr](T*) mutable { ptr.reset(); });
    }
    
  • In-place parameter pack expansion 
    template <class... T>
    void foreach(T... args) 
    {  
      bool b[] = { [=](){ 
        std::cout << args << "\n"; 
        return true; 
      }()... }; 
    }
    
    foreach(10, 20.2, true);
    
  • Memoization (see original)
    template <typename ReturnType, 
              typename... Args>
    auto memoize(ReturnType (*func)(Args...))
    {
        std::map<std::tuple<Args...>, ReturnType> cache;
    
        return ([=](Args... args) mutable  
        {
            std::tuple<Args...> t(args...);
            if (cache.find(t) == cache.end())                
            {
              std::cout << "not found\n";
              cache[t] = func(args...);
            }
            return cache[t];
        });
    }
    
  • Finally, slides




Comments

Amber said…
should `sum_of_weights` have been `count_of_weights`? (that'd make it a bit trivial). Or perhaps `count()` is the mistake

(I surely hope count doesn't sum)
Amber said…
The memoization example is nice and succinct, but it strikes me as significantly less advanced than others I've seen years ago on your blog, and even somewhat less featured than e.g. Herb's popular example.

Is there a reason you prefer this one, beyond the clarity of exposition?
Seth said…
I really like the overload example. Something like that should be in the standard library (though more general, so it works for any callable entity, not just inheritable classes.)

The 'In-place parameter pack expansion' example relies on function arguments being evaluated in a certain order. Instead you can avoid no_op(...) and do:
{bool b[] = {[=]() { cout << args << "\n"; return true; }()...};}

Nagy said…
Here is the original discussion for make_shared_ptr:

http://stackoverflow.com/questions/12314967/cohabitation-of-boostshared-ptr-and-stdshared-ptr/12315035#12315035
Sumant Tambe said…
@Amber and @Seth: Right. Thanks. I fixed the code.
y121516 said…
The Overloaded Lambdas code is ill-formed.
It work on Clang, but it is error occurred on GCC.
And behavior of GCC is correct.

Please see a entry and well-formed code written by @fimbul11
http://fimbul.hateblo.jp/entry/2014/05/10/162852
Lee said…
Nice couple of posts, Sumant. Made me want to dig into this a bit more. I've done a bit of digging, and have some more yet to do. I did find a way to compose lambdas (and, by extension, functions).

I've got a blog post on that at http://learnmeahaskell.blogspot.com/2014/05/composing-lambdas-in-c14-and-functions.html
Thanks for your ideas. You can also find the details on Affity Solutions, at the C Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.
Leopoldo said…
Muy buena.
Pagina de códigos basicos: http://tupagina.comuf.com/
Thanks for sharing this information. Python is an easy language for beginners, because there's less of an emphasis on syntax. So, if you forget your parentheses or misplace a few semicolons, it shouldn't trip you up as much as it might if you were coding in a different language.If you wanna try to check out more about learn programming C++
C and C++ Live Project Training in Delhi- RKM IT Institute is a skill enhancement coaching center that makes engineers hot property in the booming IT industry. We offer C and C++ Programming Concepts & Languages training by experts.
Syed Maroof said…
Thank you very much for the sharing! COOL.. Pakistani Bridal Dresses
Priya Kannan said…
Great site for these post and i am seeing the most of contents have useful for my Carrier.Thanks to such a useful information.Any information are commands like to share him.
Python Training in Chennai
manho valentine said…
Hello Guy
I think that Keep posting more informative articles like these one.
These are very good articles to visit...
gclub
Freddie King said…
Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
mcdonaldsgutscheine | startlr | saludlimpia
Wow great blog thank u for the explanation of concept using example program.....
Java Training Institute in Chennai
IICE-Indore said…
I am looking for some good blog sites for studying. I was searching over search engines and found your blog site.
C and C++ Training Institute in Indore

Popular posts from this blog

Multi-dimensional arrays in C++11

What new can be said about multi-dimensional arrays in C++? As it turns out, quite a bit! With the advent of C++11, we get new standard library class std::array. We also get new language features, such as template aliases and variadic templates. So I'll talk about interesting ways in which they come together.

It all started with a simple question of how to define a multi-dimensional std::array. It is a great example of deceptively simple things. Are the following the two arrays identical except that one is native and the other one is std::array?

int native[3][4];
std::array<std::array<int, 3>, 4> arr;

No! They are not. In fact, arr is more like an int[4][3]. Note the difference in the array subscripts. The native array is an array of 3 elements where every element is itself an array of 4 integers. 3 rows and 4 columns. If you want a std::array with the same layout, what you really need is:

std::array<std::array<int, 4>, 3> arr;

That's quite annoying for two r…

Understanding Fold Expressions

C++17 has an interesting new feature called fold expressions. Fold expressions offer a compact syntax to apply a binary operation to the elements of a parameter pack. Here’s an example. template <typename... Args> auto addall(Args... args) { return (... + args); } addall(1,2,3,4,5); // returns 15. This particular example is a unary left fold. It's equivalent to ((((1+2)+3)+4)+5). It reduces/folds the parameter pack of integers into a single integer by applying the binary operator successively. It's unary because it does not explicitly specify an init (a.k.a. identity) argument. So, let add it. template <typename... Args> auto addall(Args... args) { return (0 + ... + args); } addall(1,2,3,4,5); // returns 15. This version of addall is a binary left fold. The init argument is 0 and it's redundant (in this case). That's because this fold expression is equivalent to (((((0+1)+2)+3)+4)+5). Explicit identity elements will come in handy a little la…

Folding Monadic Functions

In the previous two blog posts (Understanding Fold Expressions and Folding Functions) we looked at the basic usage of C++17 fold expressions and how simple functions can be folded to create a composite one. We’ll continue our stride and see how "embellished" functions may be composed in fold expressions.

First, let me define what I mean by embellished functions. Instead of just returning a simple value, these functions are going to return a generic container of the desired value. The choice of container is very broad but not arbitrary. There are some constraints on the container and once you select a generic container, all functions must return values of the same container. Let's begin with std::vector.
// Hide the allocator template argument of std::vector. // It causes problems and is irrelevant here. template <class T> struct Vector : std::vector<T> {}; struct Continent { }; struct Country { }; struct State { }; struct City { }; auto get_countries…