Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Functor from a Lambda Function in C++

Tags:

c++

c++11

Is it possible to create a functor from a lambda function in C++?

If not, why not?

It's giving me a surprising bit of trouble to do.

Practical Use Case:

Another function requires making a functor like so:

Class::OnCallBack::MakeFunctor(this, &thisclass::function);

Typically in order to use this, I have to make a function within thisclass which means adding to the header file. After a lot of uses, there's a good bit of bloat. I want to avoid this bloat by doing something like:

Class::OnCallBack::MakeFunctor(this, 
    void callback()
    { []() { dosomething; } });

What goes wrong is compilation errors for starters. Even if it did compile, is it possible to do something like this?

like image 856
calben Avatar asked Oct 12 '25 14:10

calben


1 Answers

If you want to store the lambda function you could do it like this for a void() function

std::function< void() > callback = [](){ dosomething };

Or, for a function with a return type and parameters,

std::function< int( int ) > callback = []( int i ){ return dosomething(i);}

You'll need to include this file to use std::function though.

#include <functional>
like image 163
aslg Avatar answered Oct 14 '25 02:10

aslg