<分区>
我一直认为对于任何比较语句,即 X == Y
或 X != Y
是格式,并且您将语句链接在一起使用 &&
或 ||
。
有没有办法写 X == (Y || Z)
而不是 X == Y || X == Z
?
编辑:既然已经确定这是不可能干净利落地做到的,那还能怎么办呢?
<分区>
我一直认为对于任何比较语句,即 X == Y
或 X != Y
是格式,并且您将语句链接在一起使用 &&
或 ||
。
有没有办法写 X == (Y || Z)
而不是 X == Y || X == Z
?
编辑:既然已经确定这是不可能干净利落地做到的,那还能怎么办呢?
最佳答案
#include <algorithm>
#include <array>
#include <string>
#include <iostream>
#include <initializer_list>
template<class Type, class Next>
bool is_one_of(const Type& needle, const Next& next)
{return needle==next;}
template<class Type, class Next, class ... Rest>
bool is_one_of(const Type& needle, const Next& next, Rest... haystack)
{return needle==next || is_one_of(needle, haystack...);}
int main() {
std::string X, Y;
if (is_one_of(X, Y, "HI"))
std::cout << "it is!";
else
std::cout << "it isn't!";
return 0;
}
proof of compilation . Xeo还观察到 std::any_of
、std::all_of
和 std::none_of
可能有用,具体取决于您的实际需要和愿望.
关于c++ - 使用比较运算符时检查多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583592/