I had an idea to save time involving creating a temporary function to use as an argument to a function that needs it. The reason I’m after this behaviour is to do things in a new thread in an easy manner (using Win32 API) without having to define all kinds of functions I’ll use.
Here’s an example:
void msg (const string & message) {
MessageBox (0, message.c_str(), "Message", 0);
}
This will produce a message box, but your program is halted until it closes. The solution is to create a thread for the message box that runs concurrently with the main thread.
void msg (const string & message) {
CreateThread (0, 0,
(LPTHREAD_START_ROUTINE)({MessageBox (0, message.c_str(), "Message", 0);}),
0, 0, 0);
}
In this case, LPTHREAD_START_ROUTINE is defined as
typedef DWORD (*LPTHREAD_START_ROUTINE)(LPVOID param);
Since I have multiple functions wanting another thread for a purpose like that, putting the function in the call to CreateThread seems to be working well.
But say I wanted to use that LPVOID param. I’d like to know how standard this method is, and where I can find out how to use it for more advanced techniques. Also, I know using it in a function that will store it for later use (eg. a message loop function where you can add messages to handle and a corresponding function to call) is a bad idea as the function is temporary and would not be able to be called when needed. Is there really any use beyond things like threads where it’s annoying to make one line functions elsewhere in order to use it?
It’s called a “lambda”. They are very useful for many purposes beyond this and are in the C++11 Standard. You can find them in the latest GCC and MSVC. However, MSVC’s current implementation does not permit conversion to a function pointer, as the Standard did not specify such a conversion at that time. VC11 will implement this conversion. This code is Standard-conforming C++11: