Reputation: 17530
By Conditional Macro Expansion
, I means something like this:
XXX(_arg) => AAA(_arg), if _arg > 0
XXX(_arg) => BBB(_arg), otherwise
To be more specific, AAA and BBB are not functions but are attribute specifiers
—__attribute__ ((attribute-list))
, so runtime branching does not work.
Is is possible to write macros like this? If so, how?
Upvotes: 0
Views: 204
Reputation: 26949
The usual trick in this case is to use token-pasting in a way that makes your macros sort of "polymorphic". For example:
#define IFtrue(a,b) a
#define IFfalse(a,b) b
#define IF(x,a,b) IF##x(a,b)
IF(true, int, double) IF(false, foo(), main()) { }
Unfortunately, this works only if your "condition" is literally the word true
or the word false
; it doesn't work for things like a > 0
.
What is the exact problem you're trying to solve? There's probably a better approach.
Upvotes: 0
Reputation: 753455
I imagine that it is obvious that you can write:
#define XXX(arg) ((arg) > 0) ? AAA(arg) : BBB(arg))
This is the simple way to do it. If arg
is a compile-time constant, you will get only one of the two possible function calls in the code. If you want to try for an alternative, investigate the Boost Preprocessor package, and in particular IF
and IIF
. It works with C as well as C++.
(I renamed _arg
to arg
to avoid collisions with names reserved to the implementation. I'm not sure it actually matters in this context, but I'd steer clear of names starting with an underscore.)
Upvotes: 2