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
.
Not really
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.