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

标签 c++ operator-overloading logical-operators expression-templates

<分区>

我一直认为对于任何比较语句,即 X == YX != 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_ofstd::all_ofstd::none_of 可能有用,具体取决于您的实际需要和愿望.

关于c++ - 使用比较运算符时检查多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583592/

相关文章:

r - 降低R中的中缀运算符优先级?

c++ - 让 C++ 类充当自定义 ostream、sstream

r - 对 !is.na() 结果求和的行为

c++ - 检查函数指针类型的调用约定

c++ - 不能在指针数组中赋值

c++ - 不能只删除方法的 const 重载吗?

c++ - 矩阵类运算符重载、析构问题

python - 如果 python 中 value1 == value2 不是 None ,比较如何工作?

c++ - boost Asio : Strange when use streambuf and async_write in mutl-thread

C++通过引用传递常量值