Search code examples
c++lambdafunction-pointers

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();
}

Solution

  • 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; };