38

How can I overload the |= operator on a strongly typed (scoped) enum (in C++11, GCC)?

I want to test, set and clear bits on strongly typed enums. Why strongly typed? Because my books say it is good practice. But this means I have to static_cast<int> everywhere. To prevent this, I overload the | and & operators, but I can't figure out how to overload the |= operator on an enum. For a class you'd simply put the operator definition in the class, but for enums that doesn't seem to work syntactically.

This is what I have so far:

enum class NumericType
{
    None                    = 0,

    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
};

inline NumericType operator |(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}

inline NumericType operator &(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}

The reason I do this: this is the way it works in strongly-typed C#: an enum there is just a struct with a field of its underlying type, and a bunch of constants defined on it. But it can have any integer value that fits in the enum's hidden field.

And it seems that C++ enums work in the exact same way. In both languages casts are required to go from enum to int or vice versa. However, in C# the bitwise operators are overloaded by default, and in C++ they aren't.

7
  • 7
    I'm not sure this makes sense. The individual bits are enumerated, but PadWithZero | NegativeSign = 0x03 which is not a valid enumerated constant.
    – Useless
    Apr 8, 2013 at 21:38
  • 1
    @Useless Yeah it's just an example based on a C++11 version of a sequence of NUMERICTYPE_ defines found in Linux 0.1 used to implement printf. Does the result have to be a member of the original enumeration? I come from a C# background and expected scoped enums to behave like those in C#. Apr 8, 2013 at 21:40
  • 4
    I'm saying your enumerated type is not closed under |, so it doesn't make sense to coerce it into an (illegal value of) that type. Enumerate the flag constant values, but let a combination of flags be an int.
    – Useless
    Apr 8, 2013 at 21:43
  • 8
    @Useless - the value is not illegal. Any value that fits in the bits is okay. That kind of bit mask is done all the time, and there's nothing wrong with it. Apr 8, 2013 at 22:54
  • 1
    I'd say a combination of NumericType is a set, which is a different type than NumericType. Why don't you just create a NumericTypeSet class or something ? It would probably make much more sense semanticaly speaking.
    – ereOn
    Apr 8, 2013 at 23:31

6 Answers 6

48
inline NumericType& operator |=(NumericType& a, NumericType b)
{
    return a= a |b;
}

This works? Compile and run: (Ideone)

#include <iostream>
using namespace std;

enum class NumericType
{
    None                    = 0,

    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
};

inline NumericType operator |(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) | static_cast<int>(b));
}

inline NumericType operator &(NumericType a, NumericType b)
{
    return static_cast<NumericType>(static_cast<int>(a) & static_cast<int>(b));
}

inline NumericType& operator |=(NumericType& a, NumericType b)
{
    return a= a |b;
}

int main() {
    // your code goes here
    NumericType a=NumericType::PadWithZero;
    a|=NumericType::NegativeSign;
    cout << static_cast<int>(a) ;
    return 0;
}

print 3.

1
  • 15
    If the enum is defined inside a class, and if you want to declare the operators inside the class as well, then declare them as "friend", otherwise the compiler complains that the operators have too many arguments -- It then thinks they apply to the class and not the enum. Or declare the operators outside of the class, but then you must qualify the enum name with the class name. If enum E is defined inside class C, then operator| for the enum should be declared as "inline C::E operator|(C::E a, C::E b)" outside the class, or "friend E operator|(E a, E b)" inside the class. Nov 30, 2018 at 11:58
3

This seems to work for me:

NumericType operator |= (NumericType &a, NumericType b) {
    unsigned ai = static_cast<unsigned>(a);
    unsigned bi = static_cast<unsigned>(b);
    ai |= bi;
    return a = static_cast<NumericType>(ai);
}

However, you may still consider defining a class for your collection of enum bits:

class NumericTypeFlags {
    unsigned flags_;
public:
    NumericTypeFlags () : flags_(0) {}
    NumericTypeFlags (NumericType t) : flags_(static_cast<unsigned>(t)) {}
    //...define your "bitwise" test/set operations
};

Then, change your | and & operators to return NumericTypeFlags instead.

4
  • Your class has a hidden inner field, just like an enum. But it doesn't have its constants, so as soon as you encounter a method that expects a NumericTypeFlags you get no help from your development environment whatsoever. Apr 9, 2013 at 1:54
  • 1
    @Virtlink: It provides better type safety than a plain unsigned. It has better semantics than creating a NumericType with a value not in the enum. The implementation of the interface can make sure that only NumericType compatible arguments are used for testing and setting. In short, the help goes to the user of the class, at the cost of some work from the implementor to make it helpful to the user.
    – jxh
    Apr 9, 2013 at 2:08
  • 1
    You should (a) return a reference to the modified object and (b) always cast to the std::underlying_type of the enum, rather than assuming some fixed type will always suffice for all values that might be added or formed via bitwise. Sep 28, 2018 at 15:17
  • @underscore_d: I agree with you. The answer I provided was not directed at C++11, and properly converting the value to the appropriate unsigned underlying type for the bitwise operation would complicate the essence of the answer. A container would be a better way to capture flags, anyway. The OP should consider using bitset.
    – jxh
    Sep 28, 2018 at 17:55
2

I got sick of all the boilerplate with enum arithmetic, and moved to idioms more like this:

struct NumericType {
    typedef uint32_t type;
    enum : type {
        None                    = 0,

        PadWithZero             = 0x01,
        NegativeSign            = 0x02,
        PositiveSign            = 0x04,
        SpacePrefix             = 0x08
    };
};

This way I can still pass NumericType::type arguments for clarity, but I sacrifice type safety.

I considered making a generic template class to use in place of uint32_t which would provide one copy of the arithmetic overloads, but apparently I'm not allowed to derive an enum from a class, so whatever (thanks C++!).

2

After reading this question, I have overloaded the bitwise operators valid for all enums.

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator~(const T& value)
{
    return static_cast<T>(~static_cast<int>(value));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator|(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) | static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator|=(T& left, const T& right)
{
    return left = left | right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator&(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) & static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator&=(T& left, const T& right)
{
    return left = left & right;
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T operator^(const T& left, const T& right)
{
    return static_cast<T>(static_cast<int>(left) ^ static_cast<int>(right));
}

template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
inline T& operator^=(T& left, const T& right)
{
    return left = left ^ right;
}
3
  • Why not to use the std::underlying_type<T>::type instead of int ? Generalize everything !
    – LRDPRDX
    May 25, 2022 at 11:06
  • 1
    In C++23 we can also use std::to_underlying instead of (most) static_cast<> calls
    – ATV
    Mar 4 at 7:03
  • 1
    Pay attention std::is_enum is true for both non scoped and scoped enums. The correct is to use std::is_scoped_enum .
    – NN_
    Jun 8 at 20:42
0

By combining distinct values to make new, undefined values, you are totally contradicting the strong-typing paradigm.

It looks like you are setting individual flag bits that are completely independent. In this case, it does not make sense to combine your bits into a datatype where such a combination yields an undefined value.

You should decide on the size of your flag data (char, short, long, long long) and roll with it. You can, however, use specific types to test, set and clear flags:

typedef enum
{
    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
} Flag;

typedef short Flags;

void SetFlag( Flags & flags, Flag f )
{
    flags |= static_cast<Flags>(f);
}

void ClearFlag( Flags & flags, Flag f )
{
    flags &= ~static_cast<Flags>(f);
}

bool TestFlag( const Flags flags, Flag f )
{
    return (flags & static_cast<Flags>)(f)) == static_cast<Flags>(f);
}

This is very basic, and is fine when each flag is only a single bit. For masked flags, it's a bit more complex. There are ways to encapsulate bit flags into a strongly-typed class, but it really has to be worth it. In your case, I'm not convinced that it is.

10
  • 1
    The reason I do this: this is the way it works in strongly-typed C#: an enum there is just a struct with a field of its underlying type, and a bunch of constants defined on it. But it can have any integer value that fits in the enum's hidden field. And it seems that C++ enums work in the exact same way. In both languages casts are required to go from enum to int or vice versa. However, in C# the bitwise operators are overloaded by default, and in C++ they aren't. By the way... typedef enum { } Flag is not the C++11 syntax for enums: enum class Flag { }. Apr 8, 2013 at 22:01
  • 5
    @paddy - this kind of thing is quite common. The values that an enumerated type can represent are not restricted to the named enumerators; they can be any value that fits in the enum's bits (loosely speaking). Having to provide names for all the possible combinations here would be at best tedious. Apr 8, 2013 at 22:56
  • 4
    @ereOn - sure, if you think of an enumerated type as a set, you get constraints that aren't part of the properties of an enumerated type. You can, of course, restrict your use of enumerated types to match that restrictive model. That doesn't mean that people who use their full capabilities are abusing them. The standard was carefully written to allow exactly this sort of use. Apr 9, 2013 at 0:25
  • 2
    This was probably always destined to solicit debate. The way I see it, the semantics of an enumeration is to provide distinct values which are the only possible values for that type. I still hold that, while it's totally legit to declare the individual bits as an enumeration, it's semantically incorrect to use the same type to store a combination of those bits. When you break semantics, you go against strong typing. So you have to make a choice between the two. You cannot combine broken semantics with strong typing.
    – paddy
    Apr 9, 2013 at 0:48
  • 9
    @paddy: While you're entitled to your opinion, the C++ committee explicitly and intentionally extended the range of enums to cover all binary combinations yet left out a automatic operator|. The logic here is that you should be able to provide an operator| if and only if it makes sense, but you shouldn't need to spell out one million names for 20 combinations of flags.
    – MSalters
    Mar 16, 2015 at 16:34
0

Why strongly typed? Because my books say it is good practice.

Then your books are not talking about your use case. Unscoped enumerations are fine for flag types.

enum NumericType : int
{
    None                    = 0,

    PadWithZero             = 0x01,
    NegativeSign            = 0x02,
    PositiveSign            = 0x04,
    SpacePrefix             = 0x08
};

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.