Search code examples
c++cenumslegacy

Storing bitmask integer and enum in the same value. How?


I have a legacy type with bitmask integers (e.g. 0x0001, 0x0002, 0x0004, 0x0008, ..., 0x4000). We decided to redesign the whole thing, but with backwards compatibility. So we moved everything into an enum, including all the legacy types.

Imagine we are talking chairs. The enum now looks like this:

enum Chairs
{
    OldChair1,
    OldChair2,
    OldChair3,
    NewChair1,
    NewChair2
};

We are currently storing the chairs in a file. For the old chairs, they are stored by the bitmask integer (e.g. 1, 2, 4, 8, ..., 4000). We are now trying to store the new chairs in the same file, while maintaining backwards compatibility.

We can not write the integer value of the enum, as "4" will correspond to OldChair3 in terms of the bitmask integer, but to newChair2 in terms of the enum. As the written value has to be backwards compatible, it must correspond to OldChair3.

We came up with the idea of writing the old chairs as the bitmask integer, and the new chairs as string using some EnumToString function that I have at my disposal free-of-charge. This way, when it is an integer, we know it is an old chair, otherwise a new chair.

However, when reading the value back from the file, I do not have any StringToEnum at my disposal, nor do I want to create one. As creating a StringToEnum requires me to specify the possible enum values at more than one location. New chairs are likely added in the near future by someone else than myself.

Can anyone think of any ingenious solution as to how these old/new chairs can be written/read to/from a file in a clean way?


Solution

  • Assign different values to the new chairs so that they are not a bit mask:

    enum Chairs
    {
      OldChair1 = 0x00001,
      OldChair2 = 0x00002, 
      OldChair3 = 0x00004,
      NewChair1 = 0x80001,
      NewChair2  // 0x8002
     };