1

I'm in the process of modernizing a code base and was about to switch from old-style, nested enum definitions to Scoped Enumerations (since C++11..??)

In this particular example we're using enums for flags -
Except the compiler won't handle bitwise OR for the variant with scoped enumerations, even when explicitly providing the type as int.

Could anybody enlighten me what I'm missing here and why the two flavours of declaring enums are apparently not equivalent?

The compiler error message when using scoped enumerations is

no match for 'operator|' (operand types are 'DrawingStyle' and 'DrawingStyle')

A minimal sample snippet:

#include <iostream>

enum class DrawingStyle : int {
      Fill  =    1,
      Line  =    2
};

struct DrawingStyle2 {
 enum {
      Fill  =    1,
      Line  =    2
    };
};

int main(int argc, char * argv[])
{
#if BROKEN
    auto test = DrawingStyle::Fill | DrawingStyle::Line;
#else
    auto test = DrawingStyle2::Fill | DrawingStyle2::Line;
#endif

    std::cout << "Result: "<< test << std::endl;

    return 0;
}

Link to sample: https://godbolt.org/z/48x3ccx77

ATV
  • 4,116
  • 3
  • 23
  • 42
  • If it ain't broke, don't fix it. You'll have to provide overloaded operators for all the things you want to do with enums if you make this change. – Pete Becker Mar 03 '23 at 18:22
  • 1
    With `enum class`, the enumeration values are strongly typed and cannot be implicitly converted to integers or other enumeration types. This helps prevent subtle bugs that can occur when different enumeration types are mixed. So unless you provide an explicit `|` operator for user-defined type – ripfreeworld Mar 03 '23 at 18:23
  • 1
    Check out `std::to_underlying` aka `template [[nodiscard]] constexpr auto to_underlying(const E e) noexcept { return static_cast>(e); }` – MatG Mar 03 '23 at 18:23
  • @MatG Nice... but C++23 ;-((( – ATV Mar 04 '23 at 15:50
  • 1
    @ATV Not the implementation I posted, it's just a `static_cast` – MatG Mar 04 '23 at 15:55
  • @MatG Sure. I thought you were advocating using the new `to_underlying` which is equivalent to the latter. Not long, though.. – ATV Mar 05 '23 at 09:53

0 Answers0