I suspect that I can’t do this, but figured I’d ask the wise community here first.
I want to check if any of a handful (say ten, though probably just two or three) of variables are equal to the same specific value. e.g.
if (X == 3 || Y == 3 || Z == 3 || W == 3) ...
In Python I’m used to simply doing if 3 in (X, Y, Z, W):, but whatever.
Anyway, I’m wondering if it’s possible to abstract it into a variadic macro such as EQU_ANY(3, X, Y, Z, W) instead of writing a bunch of EQU_ANYX macros where X is the number of args.
[The solution using a macro is at the end, because it’s rather horrible and yucky.]
If you don’t mind copies being made, it’s probably cleaner to use
std::find:It’s often nice to wrap this line into a function:
used as:
In C++0x, you can use an initializer list instead of creating a temporary array:
(This works in gcc 4.5+; I’m not aware of any other compilers that support this C++0x feature yet.)
If you really want to avoid copying the objects (e.g., if they are large or expensive to copy), you can use an indirect version of the same function:
Used as:
Or, with a C++0x initializer list:
Since Jonathan Leffler mentioned Boost.Preprocessor, here is what that solution would look like:
Used as:
Which expands to:
(This is ugly and horrible; I wouldn’t use this in my code, but if you’re really worried about copies of two or three values being made, you probably don’t want to chance a function call being made either.)