I need to record (for auditing/logging purposes) the code of lambda functions that get passed around in my code. Of course, the lambda object also needs to be saved. So I came up with a macro solution 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;
}
This outputs:
CODE:
[] { cout << "Hello world!" << endl; cout << "Hello again!"; }
EXECUTION:
Hello world!
Hello again!
That is almost good, but the newlines from the lambda definition are gone (in reality my lambdas are much longer than in the above prototypical example, so keeping the newlines is needed for reasons of readability). Any ideas on how to keep them? (C++11 is fine).
Thanks!