保留换行符的C ++预处理程序字符串化? [英] C++ preprocessor stringification that preserves newlines?
问题描述
我需要记录(出于审计/记录目的)在我的代码中传递的lambda函数的代码。当然,lambda对象也需要保存。所以我想出了一个宏解决方案,如下所示:
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;
}
此输出:
CODE:
[] { cout << "Hello world!" << endl; cout << "Hello again!"; }
EXECUTION:
Hello world!
Hello again!
这几乎很好,但是lambda定义中的换行符已经消失了(实际上我的lambda很比上述典型示例更长的时间,因此出于可读性考虑,需要保留换行符)。关于如何保留它们的任何想法? (C ++ 11很好)。
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).
谢谢!
推荐答案
如果我没记错的话,新行甚至都不是传递给宏的参数的一部分。这与相对于宏扩展发生空白折叠的顺序有关,实际上是在预处理器标记化期间去除了空白。
If I remember correctly, the new lines aren't even part of the argument passed to the macro. It's to do with the order in which whitespace-folding occurs relative to macro expansion, and in effect whitespace is stripped during preprocessor tokenization.
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
所以,我认为您很不走运。您可以做一些真的讨厌的事情来解决它:
So you're out of luck, I think. You can do something really nasty to work around it:
#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
s。
Now replace the NEWLINE
s in the string before printing.
这篇关于保留换行符的C ++预处理程序字符串化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!