使用比较运算符时检查多个值

Dri*_*ise 11 c++ operator-overloading logical-operators expression-templates

我总是认为对于任何比较声明,即X == Y或者X != Y是格式,并且您将语句与&&或一起链接||.

有没有办法写X == (Y || Z)而不是X == Y || X == Z

编辑:既然已经确定这不可能干净利落,那怎么办呢?

Moo*_*uck 8

#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;
}
Run Code Online (Sandbox Code Playgroud)

汇编证明. Xeo也观察到std::any_of, std::all_of并且std::none_of可能有用,取决于您的实际需求和愿望.