C++ 位运算符后枚举上的重载相等运算符

C++ 位运算符后枚举上的重载相等运算符,c++,c++11,enums,C++,C++11,Enums,我有一个作用域枚举,我正在使用它作为位标志,我正在试图弄清楚如何在if语句中使用结果(返回布尔值) 例如: enum class Fruit { NoFruit = 0x00, Apple = 0x01, Orange = 0x02, Banana = 0x04 }; inline Fruit operator & (Fruit lhs, Fruit rhs) { return (Fruit)(static_cast<int16_t>

我有一个作用域枚举,我正在使用它作为位标志,我正在试图弄清楚如何在if语句中使用结果(返回布尔值)

例如:

enum class Fruit {
    NoFruit = 0x00,
    Apple = 0x01,
    Orange = 0x02,
    Banana = 0x04 };

inline Fruit operator & (Fruit lhs, Fruit rhs) {
    return (Fruit)(static_cast<int16_t>(lhs) & static_cast<int16_t>(rhs));
  }

在c++17中有一种方法

带有初始值设定项的If语句

if (Fruit test_fruit = Fruit::Apple; bool(test_fruit))  
{
}     
范例

#include<iostream>
#include<string>
#include<vector>
#include<map>

enum class Fruit {
    NoFruit = 0x00,
    Apple = 0x01,
    Orange = 0x02,
    Banana = 0x04 };

inline Fruit operator & (Fruit lhs, Fruit rhs) {
    return (Fruit)(static_cast<int16_t>(lhs) & static_cast<int16_t>(rhs));
}
int main()
{

    if (Fruit test_fruit = Fruit::Apple; bool(test_fruit))
    {
        std::cout<<"working"<<std::endl;
    }

}
xaxxon提供的其他示例参见注释

enum class Foo{A,B,C};
int main() {
   if (auto i = Foo::A; i < Foo::C) {}
}
enum类Foo{A,B,C};
int main(){
如果(自动i=Foo::A;i
您也可以在if中使用auto:@xaxxon感谢我从long(汇编语言)搜索此类在线工具的链接,将表达式的结果转换为
bool
bool(test_fruit&fruit::Apple)
不会
test_fruit&fruit::Apple)=fruit::NoFruit
测试与
test_fruit&fruit::Apple
相反的条件?
working
Program ended with exit code: 0    
enum class Foo{A,B,C};
int main() {
   if (auto i = Foo::A; i < Foo::C) {}
}