loading...

Introduce C++ Lambda

gapry profile image Gapry Updated on ・1 min read

Introduction

I will show three concepts of C++ Lambda in the blog post.

  • Subroutine
  • Capture by value
  • Capture by reference

Subroutine

We cannot define a routine in any existing routine.

void f(void) {
  int sum(int x, int y) {
    return x + y;
  }
}

So, we need the lambda expression. Let's rewrite the code as following.

void f(void) {
  auto sum = [](int x, int y) -> int {
    return x + y;
  };
}

Capture by value

One of the C++ Lambda features calls Capture, here is the example usage.

void f(void) {
  auto sum = [s = 1](int x, int y) -> int {
    return (x + y) << s;
  };
}

As you can see it likes function parameters, it's the capture by value.

Capture by reference

Typically, we have the call-by-value and call-by-reference in Computer Science. Just like that, we have the capture by value and capture by reference in C++.

void f(void) {
  auto s   = int(1);
  auto sum = [&](int x, int y) -> int {
    return (x + y) << s;
  };
}

The benefit of the capture by reference is that can avoid the coping overhead.

In the end

The complete source code are in my GitHub repo, here is the link.

Please follow my Twitter, GitHub, Instagram and Dev.to

  1. https://twitter.com/_gapry
  2. https://github.com/gapry/
  3. https://www.instagram.com/_gapry/
  4. https://dev.to/gapry

Thank you for reading, see you next time.

Posted on by:

gapry profile

Gapry

@gapry

Native language is Cantonese, working knowledge of English. Short term actions, long term impact. The Chinese name is 魏秋.

Discussion

markdown guide