Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact way to write if(..) statement with many equalities

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:

  • laziness of or
  • compile time loop unrolling
  • easy to extend to other operators than ==
like image 548
Ruggero Turra Avatar asked Mar 14 '16 09:03

Ruggero Turra


People also ask

How many conditions can you have in an if statement?

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...

How do you write an if statement with multiple conditions in Java?

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.

How do you pass two conditions in an if statement?

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 && .


1 Answers

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 
like image 126
Slava Avatar answered Sep 22 '22 06:09

Slava