I need to write down (for audit / logging purposes) the code of lambda functions that are passed in my code. Of course, the lambda object must also be saved. So, I came up with a solution for macros as follows:
#define LAMBDA_AND_STRING(lambda) lambda, #lambda
using namespace std;
int main(int argc, const char * argv[])
{
auto p = pair<function<void()>, string> ( LAMBDA_AND_STRING( [] {
cout << "Hello world!" << endl;
cout << "Hello again!";
} ) );
cout << "CODE:" << endl << p.second << endl << endl;
cout << "EXECUTION:" << endl;
p.first();
cout << endl;
}
It is output:
CODE:
[] { cout << "Hello world!" << endl; cout << "Hello again!"; }
EXECUTION:
Hello world!
Hello again!
This is almost good, but the new lines from the lambda definition have disappeared (in fact, my lambdas are much longer than in the above prototype example, so saving new lines is necessary for readability). Any ideas on how to save them? (C ++ 11 is fine).
Thanks!
source
share