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.