Mykola Tetiuk
Mykola Tetiuk

Reputation: 375

Another set of parentheses after a function call [C++]

I've met this as an example in a book (rewritten in a more generic form), however, the problem which I'm curious about is not explained. It works, I've tested it.

Q.:

#include <iostream>

template <typename FUNCTION>
auto compose(FUNCTION&& f)
{
    return [=](auto x){ return f(x);}; // where does the x come from?
}

int main() {
    std:: cout << compose([](int const n) { return n*2; })(4); // How is 4 captured? What is (4) here?
}

Upvotes: 1

Views: 243

Answers (1)

ypnos
ypnos

Reputation: 52337

This is just some funny code to illustrate a point I guess.

[](int const n) { return n*2; }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This code defines an anonymous function (lambda). It is transformed by the compiler to a construct similar to this one:

struct {
  operator()(int const n) { return n*2; }
};

Now compose() takes this struct and packages it in another likewise struct that has a constructor and stores the struct above in a member variable.

You end up with a call operator()(4) on an anonymous struct.

Upvotes: 2

Related Questions