C ++ preprocessor string that stores newline characters?

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!

+4
source share
1 answer

, , . , , .

foo.cpp:

#define FOO(a) a

FOO(
    one
    two
    three
)

:

$ gcc -E foo.cpp
# 1 "foo.cpp"
# 1 "<command-line>"
# 1 "foo.cpp"


one two three

, . - , :

#define LAMBDA_AND_STRING(lambda) lambda, #lambda
#define NEWLINE

LAMBDA_AND_STRING( [] { NEWLINE
    cout << "Hello world!" << endl; NEWLINE
    cout << "Hello again!"; NEWLINE
} )

:

[] { cout << "Hello world!" << endl; cout << "Hello again!"; }, "[] { NEWLINE cout << \"Hello world!\" << endl; NEWLINE cout << \"Hello again!\"; NEWLINE }"

NEWLINE .

+3

All Articles