开发者

Is it possible to set pre-processor conditions within a macro?

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.


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"


Simple, use real C++:

template <bool B> void foo_impl       (int arg) { cout << arg*5.0 << endl; }
template < >      void foo_impl<false>(int arg) { cout << arg/5.0 << endl; }
template <int I>  void foo            ( )       { foo_impl< (I>0) >(I); }  

[edit] Or in modern C++, if constexpr.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜