Search code examples
c++iife

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.:

  • What does this another set of parentheses after the function call mean?
  • How is this pattern/syntaxis called to read more about it?
#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?
}

Solution

  • 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.