在C ++ 11中对变量名进行字符串化的替代方法 [英] Alternatives to stringifying the variable name in C++11
问题描述
在我的代码中,我反复重复此表达式:
In my code, I have repeatedly this expression:
T foo;
do_sth(foo, "foo");
我正在考虑对变量名进行字符串化,例如:
I am considering stringifying the variable name, like this:
#define VARNAME(Var) (#Var)
void do_sth_new(T foo) { do_sth(foo, VARNAME(foo)); };
T foo;
do_sth_new(foo);
这是好习惯吗?在C ++ 11中,还有其他更好的选择吗?
Is it good practice? Is there any better alternative in C++11?
推荐答案
如您所示,自 VARNAME(foo)
将始终为 foo
(因为这是参数的名称)。您必须将 do_sth_new
本身写为宏:
As you show it, it doesn't work since VARNAME(foo)
will always be "foo"
(as this is the parameter's name). You have to write do_sth_new
itself as macro:
#define do_sth_new(_foo) \
do { do_sth(_foo, #_foo); } while (false)
只有这样:
T bar;
do_sth_new(bar);
生成 bar
。
不,使用预处理器是没有其他选择的,因为这是词法级的操作。您需要使用该语言在LISP级别上对AST进行修改,以提供更好的解决方案,这是不可能发生的。
And no, there is no alternative to using the preprocessor since this is an operation on the lexical level. You'd need LISP-level modification of the AST in the language to have a better solution, which is unlikely to ever happen.
这篇关于在C ++ 11中对变量名进行字符串化的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!