Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the example below the function object "rev" is defined in terms of itself. How is this possible?

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); } 
like image 818
Wake up Brazil Avatar asked Dec 15 '22 01:12

Wake up Brazil


1 Answers

The lambda captures everything by reference with [&]. This also includes rev and allows for this syntax.

like image 160
typ1232 Avatar answered May 22 '23 05:05

typ1232