Can you implement standard conformant (as described in 17.5.2.1.3 of the n3242 draft) type safe bitmasks using enum class? The way I read it, a type T is a bitmask if it support
Missing from the list are the operator != and ==
Those operators are already supported by enumeration types, integer types and std::bitset
so there's no need to overload them.
and to allow sorting one probably also wants to overload <.
Why do you want to sort bitmasks? Is (a|b) greater than (a|c)? Is std::ios::in
less than std::ios::app
? Does it matter? The relational operators are always defined for enumeration types and integer types anyway.
To answer the main question, you would implement &
as an overloaded non-member function:
Foo operator&(Foo l, Foo r)
{
typedef std::underlying_type::type ut;
return static_cast(static_cast(l) & static_cast(r));
}
I believe all the required operations for bitmask types could be defined for scoped enums, but not the requirements such as
Ci & Cj is nonzero and Ci & Cj iszero
and:
The value Y is set in the object X is the expression X & Y is nonzero.
Since scoped enums don't support impicit conversion to integer types, you cannot reliably test if it's nonzero or not. You would need to write if ((X&Y) != bitmask{})
and I don't think that's the intention of the committee.
(I initially thought they could be used to define bitmask types, then remembered I'd tried to implement one using scoped enums and encountered the problem with testing for zero/nonzero.)
Edit: I've just remembered that std::launch
is a scoped enum type and a bitmask type ... so apparently scoped enums can be bitmask types!