0

I'm attempting to overload some operators for an Enum class. I get a compiler error saying it's unable to find the operator

In Enum.h

enum class SomeEnum : unsigned
{
    Test0 = 0,
    Test1  = (1 << 0),
    Test2  = (1 << 1),
};

In Enum.cpp

#include "Enum.h"
#include <type_traits>
SomeEnum operator|(SomeEnum lhs, SomeEnum rhs)
{
    return static_cast<SomeEnum > (
        static_cast<std::underlying_type<SomeEnum >::type>(lhs) |
        static_cast<std::underlying_type<SomeEnum >::type>(rhs)
    );
}

in main.cpp

#include "Enum.h"
int main()
{
  SomeEnum blah = SomeEnum::Test1 | SomeEnum::Test2; 
}

The compiler spits out an error saying: no match for 'operator|' (operand types are 'SomeEnum ' and 'SomeEnum ')

zsnafu
  • 332
  • 3
  • 13

1 Answers1

1

You need to add declaration of operator| to Enum.h file:

enum class SomeEnum : unsigned
{
    Test0 = 0,
    Test1  = (1 << 0),
    Test2  = (1 << 1),
};

SomeEnum operator|(SomeEnum lhs, SomeEnum rhs); // added

Without this declaration in main.cpp after including Enum.h compiler can see only definition of SomeEnum, but it is not aware of presence operator| defined in Enum.cpp

rafix07
  • 20,001
  • 3
  • 20
  • 33