简体   繁体   中英

Make Functor from a Lambda Function in C++

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?

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>

You haven't specified a signature of Class::OnCallBack::MakeFunctor so I guess it's something like:

template<typename T>
Functor<T> MakeFunctor(T*, doesnt_matter (T::*)(doesnt_matter));

just because this is passed explicitly in your example.

In this case it's not a problem of C++ but of your MakeFunctor . If it would be:

template<typename F>
Functor<F> MakeFunctor(F f);

you could call it as:

Class::OnCallBack::MakeFunctor([]() { dosomething; });

There are no lambda functions in C++. The "lambda" structure in C++ defines a class with an operator() . A functor, in some. It also defines an instance of that class.

I don't know what your actual problem is, but I would guess that it has something to do with the fact that you cannot name the type of the lambda. You can usually work around this by using decltype , eg:

auto f = [](...) { ... };
typedef decltype( f ) LambdaType;

The other problem might be that every instance of a lambda, even identical instances, have different, unrelated types. Again, the solution is probably to create a named variable with a single instance of the lambda, using auto .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM