I have a simple window application with declared main window callback procedure:
WNDCLASSEXW wcx;
/* ... */
wcx.lpfnWndProc = MainWndProc;
and after the WinMain
I declared LRESULT CALLBACK MainWndProc(HWND mainWindow, UINT msg, WPARAM wparam, LPARAM lparam) { /* ... */}
and all is working ok, but I wonder is it possible to have this MainWndProc
as a lambda inside WinMain ?
You can use a lambda, provided it has no captures then it has an implicit conversion to function pointer:
#include <iostream>
typedef void (*func)();
static func some_func;
int global;
int main() {
some_func = [](){ std::cout << "Hello\n"; }; // Fine
some_func();
int local;
some_func = [&](){ local = 1; }; // Illegal - No conversion
some_func = [](){ global = 1; }; // Fine
}
The problem really is how much you can usefully do in a lambda as a callback without captures. You can still resort to "globals", in the same way you might with a regular function as the callback.
You can use a lambda, but it must not capture any variable in [ ], for example:
wc.lpfnWndProc=[](HWND h, UINT m, WPARAM w, LPARAM l)->LRESULT
{
if (m==WM_CLOSE)
PostQuitMessage(0);
else
return DefWindowProc(h,m,w,l);
return 0;
};
works in Visual C++ 2012.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With