Boost logo

Boost :

Subject: [boost] Enum Conversion
From: Roland Bock (rbock_at_[hidden])
Date: 2012-09-02 15:30:37


In a lot of projects in the company I work for we use Ice middleware
which allows to define nice interfaces for services. The IDL also allows
to define enums, but I cannot set specific values for the enum items.
We also need to store some of these values in databases. We use int to
represent the enumerations.

Since we might feel the need to add more items to an enum or delete an
unused one, we cannot just cast enum to int and vice versa when writing
to or reading from the database. We need methods that translate enum to
int and back in a stable way that won't change for an individual enum
item, even if its position in the enum changes.

I found a way to do this, which provides enum<->int and enum<->string.
It is used like this:

typedef enum
} Greek;

    (Alpha, 5),
    (Beta, 3),
    (Gamma, 7),
    (Delta, 1),
    (Epsilon, 6));

std::cout << GreekToString(IntToGreek(1)) << std::endl;
std::cout << GreekToString(IntToGreek(6)) << std::endl;
std::cout << GreekToInt(Alpha) << std::endl;
std::cout << GreekToString(Alpha) << std::endl;
std::cout << IntToGreek(17) << std::endl;


$ ./a.out
terminate called after throwing an instance of 'std::invalid_argument'
  what(): unexpected Greek value

My questions are:

a) Is this something that might be interesting for others as well? (Or
does boost even offer something like that already?)
b) I'd really like to be able to write this instead:

    Alpha = 5,
    Beta = 3,
    Gamma = 7,
    Delta = 1,
    Epsilon = 6);

Obviously, if I could use the preprocessor to translate

Alpha = 5 -> (Alpha, 5)

I'd be done. But I have no idea how to do that. Any suggestions?

Thanks and regards,


Boost list run by bdawes at, gregod at, cpdaniel at, john at