user1612986
user1612986

Reputation: 1415

c++ function definition in the argument of a function

i recently came across a part of code which looks like as follows:

static typename handle_set::iterator find(T* p)
        {
        return std::find_if(handles().begin(), handles().end(), [p](const std::unique_ptr<T,D>& l) { return l.get() == p; });
        }

where

typedef typename std::set<std::unique_ptr<T,D>> handle_set;
    static handle_set& handles(void)
    {
        static handle_set h_;

        return h_;
    }

my question is about this part:

[p](const std::unique_ptr<T,D>& l) { return l.get() == p; }

which is the 3rd argument of the function std::find_if(). The 3rd argument can be a function pointer. Is this a inline way of defining a function pointer in the argument of another function ? I haven't seen this type of usage before. Is my understanding correct ?

Thanks.

Upvotes: 2

Views: 256

Answers (4)

Matteo Italia
Matteo Italia

Reputation: 126787

std::find_if is templated and accepts as third argument a generic functor (also known as "function object"), which is whatever can be called as a function. This class of "things" includes function pointers, any object that overloads the function call operator and lambdas.

In this specific case, you are seeing it used with a lambda function, which is an anonymous function defined in place.

Lambdas are not just "a way to define a function pointer"; instead, they create a function object "on the fly" with the given code and captured context. A key difference between lambdas and "regular functions" is the fact that lambdas can capture a context (the variable p in your example).

Also, pointers to functions with the same signature have the same type, while lambdas have unspecified type. Still, a lambda that doesn't capture anything converts implicitly to an ordinary function pointer (see C++11 §5.1.2/6, thanks at Cheers and hth. - Alf for pointing this out); this makes them useful to use even with functions that accept only function pointers and not generic functors.

You probably haven't seen lambdas around yet because they are a recent addition to the C++ language (they have been standardized in the C++11 standard, approved just this year).

Upvotes: 3

Carl
Carl

Reputation: 44448

Looks like you've found some C++11 code. You're dealing with a few things there:

  1. Lambda functions
  2. Unique Pointers
  3. Closures

You need to do some reading up to understand exactly what that code does.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145249

It's a C++11 lambda (anonymous function).

Upvotes: 1

Puppy
Puppy

Reputation: 146910

The 3rd argument is not a function pointer. It is a function object. That object may happen to be a pointer. But it might not. It may be any value which has operator(). A lambda is such a value.

Upvotes: 1

Related Questions