Search code examples
c++enumslanguage-lawyerscoped-enums

Use of an overloaded operator in a scoped enum definition


Given this code

#include <iostream>
#include <format>

enum class Enum;

constexpr Enum operator~(Enum) { return static_cast<Enum>(5); }

enum class Enum { A = 1, B = ~Enum::A }; // line 8
//                            ^^^^^^^

int main() {
    std::cout << std::format("{} and {}\n",
        static_cast<int>(Enum::B), static_cast<int>(~Enum::A));
}

is there a way to tell the compiler not to treat Enum::A on line 8 as int, but rather as of type Enum? In other words, to force the compiler to use the custom operator~(). This program outputs -2 and 5.


Solution

  • Not really

    If the underlying type is fixed, the type of each enumerator prior to the closing brace is the underlying type and the constant-expression in the enumerator-definition shall be a converted constant expression of the underlying type.

    If you want to execute some custom logic reliably, lift it out of the operator into a constexpr named function the accepts that the underlying type, then reuse it for both the enum declaration and the operator definition.