Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload cast operator between two enums

Tags:

c++

enums

casting

Is there a way to overload a cast operator to convert between two enums?

In my code I have

enum devStatus
{
    NOT_OPERATING,
    INITIALISING,
    DEGRADED,
    NORMAL
};

enum dataStatus
{
    UNAVAILABLE = 1,
    DEGRADED,
    NORMAL
}

where NOT_OPERATING and INITIALISING map to UNAVAILABLE; DEGRADED and NORMAL map straight across. These are fixed by external interfaces.

I am looking for a way to convert between devStatus and dataStatus and would like to be able to write something like:

devStatus devSts;
getDeviceStatus(&devSts);
dataStatus dataSts = (dataStatus)devSts;

I know that if these were classes, I could write devStatus::operator dataStatus() to do this. Is there a way of doing this for a enums?

I could just have a free function dataStatus devStatus2dataStatus(const devStatus& desSts)

like image 542
DanS Avatar asked Sep 05 '11 18:09

DanS


1 Answers

In C++, conversion operators can only be declared within class, struct, and union declarations. They cannot be declared outside the type (like operator+, for example). Enum type declarations do not support instance members, so you will need to go with the conversion function. Doing so will also make the calling code clearer. The following example demonstrates this, using custom namespaces to scope the enumerations and conversion functions:

namespace TheirEnum {
   enum Type {
      Value1,
      Value2
   };
}
namespace MyEnum {
   enum Type {
      Value1,
      Value2
   };

   TheirEnum::Type ToTheirEnum (Type e) {
      switch (e) {
         case Value1: return TheirEnum::Value1;
         case Value2: return TheirEnum::Value2;
         default: throw std::invalid_argument("e");
      }
   }
}

// usage:
TheirEnum::Type e = MyEnum::ToTheirEnum(MyEnum::Value1);
like image 186
Brent M. Spell Avatar answered Nov 20 '22 00:11

Brent M. Spell