简体   繁体   中英

How to assign a lambda function to struct member, when the function must access other members?

I would like to code a utility function pointer inside my object that calls a group of other functions in the object. This utility function pointer should be initialized with default functionality, but be capable of override as well.

This is what I have so far:

struct GameState {
    void(*setup)()          = [](){};
    void(*handleInput)()    = [](){};
    void(*update)()         = [](){};
    void(*draw)()           = [](){};
    void(*run)() = [this]() { handleInput(); update(); draw(); };
}

The compiler doesn't like the use of this in the capture of my lambda function and spits out the following errors all for that line:

E0413 - no suitable conversion function from "lambda []void ()->void" to "void (*)()" exists

C2440 'initializing': cannot convert from 'GameState::' to 'void (__cdecl *)(void)'

C2439 'GameState::run': member could not be initialized

The problem is that the types mismatch.

 void(*run)() = [this]() { handleInput(); update(); draw(); }; }

You are assigning a lambda to a function pointer. A lambda is not a function pointer, and is actually an instance of a class that overrides operator() . This object also captures this in your example .

The

void(*setup)() = [](){};

Compiles because there is no capture. When there is no capture, there is no state and the lambda can be treated as a pointer and not as a class instance.

If it was allowed by the language, you'd like something like

// error
auto run  = [this]() { handleInput(); update(); draw(); };·

But that syntax is not supported in this context. And since the type of the lambda object is unknown to the programmer, there is no way to write its type.

Instead, what will work is something like:

std::function<void()>run  = [this]() { handleInput(); update(); draw(); };

This is not as efficient as defining run with the type of the lambda, since std::function will most likely store the lambda on the heap.

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