是否可以在宏中设置预处理器条件?
我所处的位置是,这种设计将极大地提高代码的清晰度和维护需求。
我正在寻找的是这样的:
#define MY_MACRO(arg) #if (arg)>0 cout<<((arg)*5.0)<<endl; #else cout<<((arg)/5.0)<<endl; #endif
这里的想法:
预处理器根据宏参数的编译时(常量)值替换不同的代码行。当然,我知道这种语法不起作用,因为 #
被视为字符串化运算符而不是标准的 #if
,但我认为这演示了我正在努力实现的预处理器功能。
我知道我可以在其中放置一个标准的 if 语句,然后编译器/运行时将检查该值。但这对于应用程序来说是不必要的工作,因为 arg
始终会传递一个常量值,例如仅需要计算的 10.8
或 -12.5
在编译时。
这种数字运算应用程序的性能需求要求尽可能消除所有不必要的运行时条件,并且使用了许多常量值和宏(代替变量和函数)来实现这一点。如果能够继续这种趋势,而无需将预处理器代码与真正的 if
条件混合在一起,将使代码变得更加干净 - 当然,代码清洁度是使用宏时最大的问题之一,尤其是在这个级别。
I'm in a position where this design would greatly improve the clarity and maintenance-needs for my code.
What I'm looking for is something like this:
#define MY_MACRO(arg) #if (arg)>0 cout<<((arg)*5.0)<<endl; #else cout<<((arg)/5.0)<<endl; #endif
The idea here:
The pre-processor substitutes different lines of code depending on the compile-time (constant) value of the macro argument. Of course, I know this syntax doesn't work, as the #
is seen as the string-ize operator instead of the standard #if
, but I think this demonstrates the pre-processor functionality I am trying to achieve.
I know that I could just put a standard if
statement in there, and the compiler/runtime would be left to check the value. But this is unnecessary work for the application when arg
will always be passed a constant value, like 10.8
or -12.5
that only needs to be evaluated at compile-time.
Performance needs for this number-crunching application require that all unnecessary runtime conditions be eliminated whenever possible, and many constant values and macros have been used (in place of variables and functions) to make this happen. The ability to continue this trend without having to mix pre-processor code with real if
conditions would make this much cleaner - and, of course, code-cleanliness is one of the biggest concerns when using macros, especially at this level.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,您的宏中不能包含
#if
(或类似的内容)。但是,如果在编译时已知条件,则可以安全地使用普通的
if
语句。编译器将对其进行优化(假设您打开了优化)。它被称为“死代码消除”
As far as I know, you cannot have
#if
(or anything similar) inside your macro.However, if the condition is known at compile-time, you can safetly use a normal
if
statement. The compiler will optimise it (assuming you have optimisions turned on).It's called "Dead code elimination"
简单,使用真正的 C++:
[编辑]
或者在现代 C++ 中,
if constexpr
。Simple, use real C++:
[edit]
Or in modern C++,
if constexpr
.