Overloading bitwise operators on scoped enum bit flags

Question | Jan 20, 2017 | rparekh 

We are creating an API interface for applications to get price ticks of financial assets (e.g stocks). The API interface looks as below:

enum class Ticks : uint8_t {
 None = 0x00,
 Bid  = 0x01,
 Offer = 0x02,
 Trade = 0x04  
};

// In C++14 you can use std::underlying_type_t below
using Ticks_t = std::underlying_type<Ticks>::type;

void RequestTicks( Ticks_t tickTypes 
                   /*, more parameters like stock symbol and callback */ );

We have defined different tick types as scoped enum (enum class) bit flags. Depending on required tick types the client applications would pass bitwise ORed Ticks flags to RequestTicks. The RequestTicks would return the data through a callback method, that detail is not relevant here.

This is how we want a typical call to RequestTicks to look like:

RequestTicks( Ticks::Bid | 
              Ticks::Offer 
             /* more params */ );  // ERROR

As the scoped enums are strongly typed they are not implicitly converted to integral types. The above call to RequestTicks would not compile without the explicit casting of Ticks constants to Ticks_t (uint8_t here):

RequestTicks( static_cast<Ticks_t>(Ticks::Bid) | 
              static_cast<Ticks_t>(Ticks::Offer) 
              /* more params */ );  // OK

Similar casting would be done in RequestTicks too to determine the requested tick types. To avoid the explicit cast we are going to overload some bitwise operators on Ticks:

inline Ticks_t operator | (Ticks t1, Ticks t2) {
 return  static_cast<Ticks_t>(t1) | static_cast<Ticks_t>(t2);
}

Now the following code would compile fine:

// client calls
RequestTicks( Ticks::Bid | 
              Ticks::Offer 
              /* more params */ );

Here is the exercise. Within RequestTicks we want to detect the requested tick types by bitwise ANDing Ticks_t and Ticks in any order:

 void RequestTicks(Ticks_t tickTypes /*more params*/) {
   if(tickTypes & Ticks::Bid) {  /*get bids*/  }
   if(Ticks::Offer & tickTypes) {  /*get offers*/  }        
   // ....
 }

Select the correct implementations of required bitwise AND ('&') operator within RequestTicks on Ticks_t and Ticks: