User12547645
User12547645

Reputation: 8507

C++: What is the use case of Lambda to function pointer conversion?

You can convert Lambdas to function pointers. What are the practical use cases for this? Why do we need this?

Play with it

int main() {
    auto test = []() -> int { return 1; };
    using func_point = int (*)();
    func_point fp = test;
    return test();
}

Upvotes: 0

Views: 143

Answers (2)

Markus Mayr
Markus Mayr

Reputation: 4118

Alternatives to function pointers are std::function and template parameters / generic functors. All of those impact your code in different ways.

You can pass lambdas to code that expects either std::function, generic functors or function pointers. It is convenient to have a single concept in the calling code that supports all those different interface concepts so consistently and after all, convenience is all, lambdas are about.

Just to make this complete:

  • function pointers are the least universal concept of the ones above, so not every lambda can be turned into a function pointer. The capture clause must be empty.
  • Prefixing lambdas with a + explicitly casts them to a function pointer, if possible, i.e. in the following snippet, f has the type int (*)( int ): auto f = +[]( int x ) { return x; };

Upvotes: 1

Andrey Semashev
Andrey Semashev

Reputation: 10644

First, you can only convert lambdas with empty closure. Such lambdas are effectively stateless, which makes the conversion possible.

As for the use cases, one important use case is integration with C. There are plenty C APIs, which allow registration of user callbacks, usually taking one or more arguments, like this:

// Registers callback to be called with the specified state pointer
void register_callback(void (*callback)(void* state), void* state);

You can associate the state with a C++ class instance and translate the callback invokation to a method call:

class Foo
{
public:
    void method();
};

Foo foo;
register_callback([](void* p) { static_cast< Foo* >(p)->method(); }, &foo);

Upvotes: 2

Related Questions