Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I have main window procedure as a lambda in WinMain?

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 ?

like image 777
rsk82 Avatar asked Jan 12 '13 11:01

rsk82


2 Answers

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.

like image 106
Flexo Avatar answered Sep 20 '22 20:09

Flexo


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.

like image 35
Azarien Avatar answered Sep 24 '22 20:09

Azarien