0

I have a scoped enum that I am using as bit flags and I am trying to figure out how to use the results in an if statement (return boolean)

Example:

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

Is it possible to below I without writing == Fruit::NoFruit, right now I get the error "expression must have bool type (or be convertible to a bool)"

Fruit test_fruit = Fruit::Apple;
// Not possible, have to write 
// if((test_fruit & Fruit::Apple) == Fruit::NoFruit)
if(test_fruit & Fruit::Apple) {
    // do something
 }
user2840470
  • 919
  • 1
  • 11
  • 23
  • Wouldn't `test_fruit & Fruit::Apple) == Fruit::NoFruit` test for the opposite condition as `test_fruit & Fruit::Apple`? – AndyG Aug 22 '17 at 02:21

1 Answers1

1

In c++ 17 there is a way

If Statements with Initializer

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

Example

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

}

Output

working
Program ended with exit code: 0    

Other Example as provided by xaxxon see comment

enum class Foo{A,B,C};
int main() {
   if (auto i = Foo::A; i < Foo::C) {}
}
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52