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
- https://twitter.com/_gapry
- https://github.com/gapry/
- https://www.instagram.com/_gapry/
- https://dev.to/gapry
Thank you for reading, see you next time.
Top comments (0)