使用比较运算符时检查多个值 [英] Check for multiple values when using comparison operators
问题描述
我一直给人的印象是,对于任何比较语句,即X == Y
或X != Y
是格式,并且您将语句与&&
或||
链接在一起.
I've always been under the impression that for any comparison statement, i.e. X == Y
or X != Y
is the format, and you chain statements together with &&
or ||
.
有没有什么方法可以代替X == Y || X == Z
来编写X == (Y || Z)
?
Is there not some way to write X == (Y || Z)
instead of X == Y || X == Z
?
编辑:由于已经确定不可能做到这一点,所以还可以怎么做?
Edit: Since it has been established that this is not possible to do cleanly, how else could it be done?
推荐答案
#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;
}
编译证明. Xeo 还会观察到std::any_of
,std::all_of
和std::none_of
可能有用,具体取决于您的实际情况.需求和欲望.
proof of compilation. Xeo also observes that std::any_of
, std::all_of
and std::none_of
may have been useful, depending on your actual needs and desires.
这篇关于使用比较运算符时检查多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!