简体   繁体   中英

passing lambda as a constructor argument

I am trying to store a callback function in a class, so I can create different instances with different callback. Unfortunately stackoverflow forces me to write more useless stuff, saying my post is mostly code. However I don't see any troubles instantly understand my question by looking at the code below.

Can't understand why this doesn't work:

#include <iostream>
#include <functional>

class A {
    public:
        A(std::function<void()> lambda) : lambda_{lambda} {};
        void Run() { lambda_(); };
    private:
        std::function<void()> lambda_;
};

auto main() -> int {
    auto q = []{};    
    A(q) a;                                                                                                                                                                                                        
    a.Run();
}

Error:

1.cpp:15:10: error: expected ‘;’ before ‘a’
     A(q) a;
          ^

While this does:

#include <iostream>
#include <functional>

void A(std::function<void()> lambda) {
    lambda(); 
};

auto main() -> int {
    auto q = []{};

    A(q);
}

The syntax for passing constructor arguments in a variable declaration is:

A a(q);

More generally, the different ways of declaring variables are:

TypeName ;    // no arguments
TypeName ();  // WRONG: this is a function declaration
TypeName (arg1, arg2, ...);

And with C++11 uniform initialization :

TypeName {};  // no arguments
TypeName {arg1, arg2, ...};

The correct syntax for initializing an object a with parameter q is

A a(q);

not

A(q) a;

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