This example (void function f(string& s1, string& s2)
) was taken from page 297/298 of B.Stroustup's new book "TCPL" 4th edition.
#include <iostream>
#include <functional>
#include <string>
#include <algorithm>
void f(std::string& s1, std::string& s2)
{
std::function<void(char* b, char* e)> rev =
[&](char* b, char* e) { if (1<e-b) { std::swap(*b,*--e); rev(++b,e); } };
rev(&s1[0],&s1[0]+s1.size());
rev(&s2[0],&s2[0]+s2.size());
}
int main()
{
std::string s1("Hello");
std::string s2("World");
f(s1, s2);
std::cout << s1 << " " << s2 << '\n';
}
The code compiles and prints out the correct results, i.e., function f
reverses the characters of the input strings. Program output:
olleH dlroW
I can understand the semantics of the expression below. My problem is to accept its syntax, as the variable rev
is defined in terms of itself.
std::function<void(char* b, char* e)> rev =
[&](char* b, char* e) { if (1<e-b) { std::swap(*b,*--e); rev(++b,e); }
The lambda captures everything by reference with [&]
. This also includes rev
and allows for this syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With