Is there a better way to write code like this:
if (var == "first case" or var == "second case" or var == "third case" or ...)
In Python I can write:
if var in ("first case", "second case", "third case", ...)
which also gives me the opportunity to easily pass the list of good options:
good_values = "first case", "second case", "third case" if var in good_values
This is just an example: the type of var
may be different from a string, but I am only interested in alternative (or
) comparisons (==
). var
may be non-const
, while the list of options is known at compile time.
Pro bonus:
or
==
Technically only 1 condition is evaluated inside an if , what is ascually happening is 1 condition gets evaluated and its result is evaluated with the next and so on...
When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.
You can have two conditions if you use the double bars( || ). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute. If you want all of conditions to be true use && .
if you want to expand it compile time you can use something like this
template<class T1, class T2> bool isin(T1&& t1, T2&& t2) { return t1 == t2; } template<class T1, class T2, class... Ts> bool isin(T1&& t1 , T2&& t2, T2&&... ts) { return t1 == t2 || isin(t1, ts...); } std::string my_var = ...; // somewhere in the code ... bool b = isin(my_var, "fun", "gun", "hun");
I did not test it actually, and the idea comes from Alexandrescu's 'Variadic templates are funadic' talk. So for the details (and proper implementation) watch that.
Edit: in c++17 they introduced a nice fold expression syntax
template<typename... Args> bool all(Args... args) { return (... && args); } bool b = all(true, true, true, false); // within all(), the unary left fold expands as // return ((true && true) && true) && false; // b is false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With