0

I'm confused about the use of square brackets around [funcParam] in the C++11 code segment below:

typedef std::function<std::vector<OtherType> ()> FuncPtr;

inline void create(FuncPtr funcParam)
{
    auto create_evaluator = [funcParam] ()
    {
        return anotherFunction(funcParam());
    };
    // ...
}

The code above it called by this line (somewhat simplified to keep it readable):

create( [] () { return CONSTANT; } );

Can someone explain the use of brackets in both situations? In the calling code, it looks to be used to create a function without a name. What's it doing in the first segment? Thanks!

Kayvon
  • 3
  • 2

1 Answers1

1

create_evaluator is a lambda expression (check out the examples at the bottom of that page).

In the case of

auto create_evaluator = [funcParam] ()
{
    return anotherFunction(funcParam());
};
  • [funcParam] is a variable in the local scope that is captured by the lambda function and therefore available to be reference within the lambda function when it is called elsewhere.

  • () denotes the arguments to the lambda function (none in this case)

  • { return anotherFunction(funcParam()); } is the body of the lambda function.

With the call

create( [] () { return CONSTANT; } );

create is called with another lambda expression as its argument. That lambda argument

  • captures nothing: []
  • has no arguments: ()
  • has the body: { return CONSTANT; }
zane
  • 58
  • 6