简体   繁体   中英

C++ - std::function as parameter for a functor

I wrote an Event class as a wrapper around callback functions, implemented as std::function s. This is what it looks like:

class Event
{
public:
    Event() : default_handler([]() {});
    Event(const std::function<void()> handler) : default_handler(handler);

    void SetHandler(std::function<void()> handler)
    {
        custom_handler = handler;
    }

    void operator()(void)
    {
        default_handler();
        custom_handler();
    }

private:
    const std::function<void()> default_handler;
    std::function<void()> custom_handler;
};

Then, inside another class, I have an instance of an Event:

class Control
{
public:
    Control();

//Should call constructor Event()
    Event myEvent1;
//Should call constructor Event(std::function<void()>)
    Event myEvent2([]() {/*do stuff... */})
};

This, however, won't compile on VC++, generating error C3646 (unknown override specifier) and error C4430 (missing type specifier - int assumed) for both handlers, with more syntax errors for myEvent2. Where did I go wrong?

When you write

Event myEvent2([]() {/*do stuff... */});

compiler treats myEvent2 as the member function, not constructor call.

You should use {} syntax:

Event myEvent2{[]() {/*do stuff... */}};

Demo

As syntax for default member initializer is

member = value;

or

member{value};

but NOT

member(value); // Invalid syntax

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