6

An appropriate way to manage enumeration with associated strings

 2 years ago
source link: https://www.codesd.com/item/an-appropriate-way-to-manage-enumeration-with-associated-strings.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

An appropriate way to manage enumeration with associated strings

advertisements

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?


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
}

Tags enums

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK