位运算符

时间:2017-08-22 01:18:25

标签: c++ c++11 enums

我有一个scoped enum,我用它作为位标志,我试图找出如何在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));
  }

是否有可能在I以下没有写== Fruit :: NoFruit,现在我得到错误&#34;表达式必须有bool类型(或者可以转换为bool)&#34;

Fruit test_fruit = Fruit::Apple;
// Not possible, have to write 
// if((test_fruit & Fruit::Apple) == Fruit::NoFruit)
if(test_fruit & Fruit::Apple) {
    // do something
 }

1 个答案:

答案 0 :(得分:1)

在c ++ 17中有一种方法

如果带有初始化程序的语句

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;
    }

}

输出

working
Program ended with exit code: 0    

xaxxon 提供的其他示例请参阅评论

enum class Foo{A,B,C};
int main() {
   if (auto i = Foo::A; i < Foo::C) {}
}