Search⌘ K

Assigning C Function Pointers to Lambdas

Explore how to convert lambdas without captures to C function pointers using the plus operator. Understand why lambdas with captures have unique types and how to store them with std::function. This lesson helps you handle callbacks in C++ effectively when integrating with C libraries or legacy code.

Lambdas as function pointers

Lambdas without captures can be implicitly converted to function pointers. Let's say we are using a C library, or an older C++ library, that uses a callback function as a parameter, like this:

C++
extern void download_webpage(const char* url,void (*callback)(int, const char*));

The callback is called with a return code and some downloaded content. It is possible to pass a lambda as a parameter when calling download_webpage(). Since the callback is a regular function pointer, the lambda must not have any captures and we have to ...