remudada
remudada

Reputation: 3791

Proper way to handle enum with associated strings

I sometimes run into situations where i have an enum that has a string constant associated with it and at points in the code I have to replace the enum with the string. e.g.

An enum in my code

typedef enum {
    //define weapon names
    kWeaponGaussRifleType = 1,
    kWeaponGatlingGunType,
    kWeaponSideWinderMissileType,
    kWeaponLaserType
} WeaponType;

Common use for that enum which is perhaps ok.

void fireWeapon(WeaponType w) {
    switch(w) {
        ...
    }
}

Possible incorrect use of that enum which I would like to fix.

void loadAsset(WeaponType w) {
    //associate weapon filename with the weapon type
    if(w == kWeaponGaussRifleType) {
       fileName = "gaussRifle.png"
    } elseif { 
       ...
    }
}

Obviously this code above can be replaced with a switch or it could pick names from an array of strings. But it would still mean that I have to define the entity name twice (once in the enum and then in the code where the translation occurs) and this is thus prone to error and inconsistency in naming.

Is there any way in C++ to fix this?

Upvotes: 1

Views: 224

Answers (2)

Vicky
Vicky

Reputation: 13244

Yes, you could use X-Macros.

In your header file you define something like this:

#define weapons_list \
X(kWeaponGaussRifleType, 1, "gaussRifle.png") \
X(kWeaponGatlingGunType, 2. "gatlingGun.png") 

Then when you want to define the type:

#define X(a,b,c) a = b;
typedef enum {
    weapons_list
} weaponType;
#undef X

Then your other example:

void loadAsset(WeaponType w) {
    //associate weapon filename with the weapon type
#define X(a,b,c) if (w == a) { fileName = c; }
    weapons_list
#undef X
}

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 612954

But it would still mean that I have to define the entity name twice (once in the enum and then in the code where the translation occurs) and this is thus prone to error and inconsistency in naming. Is there any way in C++ to fix this?

There are no language features in C++ that allow you to recover a textual representation of an enum value. There is no way to avoid the duplication.

Upvotes: 1

Related Questions