3
class myClass
{
    enum firstEnum { Value1, Value2, Value3};
    enum secondEnum { ValueA, ValueB, ValueC};
};

I want to overload the | operator on the two enums above. Is it possible?

Notice that there are two enums here, not just one and i want to overload the | for both.

Thanks.

YAA
  • 409
  • 1
  • 5
  • 11
  • possible duplicate of [Operators overloading for enums](http://stackoverflow.com/questions/2571456/operators-overloading-for-enums) – xxbbcc Sep 17 '15 at 18:50
  • What are you trying to do? Overloading the `|` can lead to massive confusion, especially for enums. – xxbbcc Sep 17 '15 at 18:51

1 Answers1

4

Yes, just like you can for regular functions, you can overload operators for different types of arguments

#include <iostream>

struct myClass
{
    enum firstEnum { Value1, Value2, Value3};
    enum secondEnum { ValueA, ValueB, ValueC};

    friend void operator|(firstEnum L, firstEnum R) { std::cout << "first\n"; }
    friend void operator|(secondEnum L, secondEnum R) { std::cout << "second\n"; }
};

int main()
{
    myClass::Value1 | myClass::Value2; // first
    myClass::ValueA | myClass::ValueB; // second
    myClass::Value1 | myClass::ValueA; // prints nothing, converts enums to builtin operator|(int, int)
}

Live Example.

But be careful with old-fashioned enum, they implicitly convert to integral types so that mixed calls to operator| will be calling the builtin operator| on int. Use C++11 enum class to get more type-safe behavior.

Update: the above code compiles for C++98 as well, it's just that C++11 offers more type-safe enums.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • Unfortunately, I am using C++98, so I cannot use enum class. Thanks for the answer. – YAA Sep 17 '15 at 18:54
  • @Yanniel He is not using `enum class`. he is using a `class` that has an `enum` which is C++98 compliant. [here](http://coliru.stacked-crooked.com/a/e1e60514b4e62e9c) is the live example in C++98 compilation – NathanOliver Sep 17 '15 at 18:55
  • 2
    Yes, TemplateRex's solution works in C++98; but he also said "Use enum class to get more type-safe behavior", hence my previous comment. – YAA Sep 17 '15 at 19:00
  • 1
    @NathanOliver updated to avoid confusion about c++98. – TemplateRex Sep 17 '15 at 19:08