Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a lambda for later callback?

Tags:

c++

c++11

lambda

How do I fix the code below to store a lambda so I can invoke it at a later time?

The error I currently get is field 'm_callback' has incomplete type.

class Foo
{
    public:
        Foo()  { }
        ~Foo() { }

        template< typename FuncT > 
        void setCallback( FuncT&& callback )
        {
            m_callback = callback;
        }

    private:
        auto m_callback;   // this line is broken
};
int main(int argc, char** argv)
{
    Foo foo;

    foo.setCallback( [] (int x){ return true; } );

    return 0;
}
like image 589
kfmfe04 Avatar asked Jun 07 '26 20:06

kfmfe04


2 Answers

The auto keyword can't be used liked that. I recommend using something like this:

#include <functional>
std::function<bool (int)> m_callback;

This is done from Visual Studio 2010.

like image 167
linuxuser27 Avatar answered Jun 09 '26 08:06

linuxuser27


The auto keyword can only be used in conjunction with an initalization expression.

So... this works:

auto callback = [](int x){ return x == 0; };

... but this doesn't:

auto callback;
callback = [](int x){ return x == 0; };

I would recommend that you use something like function with a specific signature to represent a callback.

like image 41
bobbymcr Avatar answered Jun 09 '26 09:06

bobbymcr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!