开发者

Overload cast operator between two enums

开发者 https://www.devze.com 2023-04-03 07:18 出处:网络
Is there a way to overload a cast operator to convert between two enums? In 开发者_StackOverflowmy code I have

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

In 开发者_StackOverflowmy 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)


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消