Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have an operator= for an enum?

I have an enum, but I want to have an assignment operator for it to be able to assign a type that is not of the original enum. E.g.

enum class X : int
{
  A, B, C, D
}

enum class Y : char
{
  A, B, C, D
}

Y& operator=(Y& lhs, X rhs)
{
  return Y = static_cast<Y>(X);
}

But I'm getting an 'operator =' must be a non-static member. Is there no way to do this?

like image 521
Adrian Avatar asked Oct 21 '25 05:10

Adrian


1 Answers

You cannot because, as the error message tells you, operator= can only be a non-static member function, and enums can't have members. If you really want to be able to assign from a different enum, maybe you should just make Y a class. Another possibility is to write a helper function to perform the assignment.

like image 63
Brian Bi Avatar answered Oct 22 '25 18:10

Brian Bi