It looks like you'd like to chain the or
s in this:
if (number==1||2||3)
The above should be written as
if (number==1 || number==2 || number==3)
or, by checking if number
is in the range [1,3]
:
if (number>=1 && number<=3)
If you'd like to chain many or
s (that are not ranges), you could create a helper template function using a fold expression (C++17):
Example:
#include <functional> // std::equal_to
#include <iostream>
// matching exactly two operands
template<class T, class BinaryPredicate>
inline constexpr bool chained_or(const T& v1, BinaryPredicate p, const T& v2)
{
return p(v1, v2);
}
// matching three or more operands
template<class T, class BinaryPredicate, class... Ts>
inline constexpr bool chained_or(const T& v1, BinaryPredicate p, const T& v2,
const Ts&... vs)
{
return p(v1, v2) || (chained_or(v1, p, vs) || ...); // fold expression
}
int main() {
// check if 6 is equal to any of the listed numbers
if constexpr (chained_or(6, std::equal_to<int>(), 1,3,4,6,9)) {
std::cout << "6 - true\n";
}
// check if 7 is any of the listed numbers
if constexpr(chained_or(7, std::equal_to<int>(), 1,3,4,6,9)) {
std::cout << "7 - true\n";
}
}
When chained_or
is instantiated, the fold expressions will unfold to:
(6 == 1 || 6 == 3 || 6 == 4 || 6 == 6 || 6 == 9) // true
and
(7 == 1 || 7 == 3 || 7 == 4 || 7 == 6 || 7 == 9) // false