Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Simpler way to compare an integer with a hard coded set of integers

Tags:

c++

I am using C++ for particle physics and I find myself commondly writing lines like this:

bool isItCorrect(int i){
 if(i==11 || i == 62 || i==-11 || i == 11002 || i==22002) return True
 else return false;
}

What is the easiest way for me to make this shorter in C++. In python I could do:

def isItCorrect( i ):
    if (i is in [11,62,-11,11002,22002]) return True
    else return False
like image 514
Tsangares Avatar asked Oct 27 '25 13:10

Tsangares


1 Answers

You can use variadic templates in C++ 11 and define:

template <typename T, typename T1>
bool isItCorrect(T t, T1 t1) {
  return t == t1;
}
template <typename T, typename T1, typename... T2>
bool isItCorrect(T t, T1 t1, T2... t2) {
  return t == t1 || isItCorrect(t, t2...);
}

and use:

bool isItCorrect(int i) {
    return isItCorrect(i, 62, -11, 110022, 22002);
}
like image 172
mahdi_12167 Avatar answered Oct 29 '25 03:10

mahdi_12167



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!