Reputation: 8507
You can convert Lambdas to function pointers. What are the practical use cases for this? Why do we need this?
int main() {
auto test = []() -> int { return 1; };
using func_point = int (*)();
func_point fp = test;
return test();
}
Upvotes: 0
Views: 143
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:
+
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
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