Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum as argument returning string

Tags:

c++

string

enums

My current program uses 3 different enums:

enum ThingEnum{
    Thing1 = 0,
    Thing2 = 1,
    Thing3 = 2,
    OtherThing = 3
};
enum ReturnEnum {
    Success = 4,// the method did what it is supposed to
    Error1 = 5,// an error occured
    Error2 = 6,// an error occured
    Error3 = 7,// an error occured
    Error4 = 8,// a fatal error occured program must terminate
    Pointer = 9// the method may need to be called again
};
enum TypeEnum {
    Type1 = 10,
    Type2 = 11,
    Type3 = 12,
    Type4 = 13,
    OtherType = 14
};  

What I want to do is create a global function that takes an enum and returns a string (as the value of an enum is really just a specialized variable name that always has a value). Is it possible to create a function that takes a generic enum? e.g.

string enumToString (enum _enum){}

or would I have to make a function for each different enum? Just a possible thought I did some reading, and some compilers allow for a Enum to resolve to an int so could I pass the enum as an int and then work with it?

like image 455
gardian06 Avatar asked Dec 17 '25 16:12

gardian06


1 Answers

There are two options of "ToString-like" function implementation:

  1. Implement a simple static switch-case function.

Code:

std::string ThingEnumToString(ThingEnum thing)
{
    switch (thing) {
    case Thing1:
        return std::string("Thing1");
    case Thing2:    
        return std::string("Thing2");
    case Thing3:
        return std::string("Thing3");        
    case OtherThing:
        return std::string("OtherThing");
    default:
        throw std::invalid_argument("thing");
        break;
    }
}
  1. Implement a static function with a dictionary lookup.

Code:

typedef std::map<ThingEnum, std::string> ThingsMap;

static ThingsMap GetThingsMap()
{
    ThingsMap things_map;
    things_map.insert(ThingsMap::value_type(Thing1, std::string("Thing1")));
    things_map.insert(ThingsMap::value_type(Thing2, std::string("Thing2")));
    things_map.insert(ThingsMap::value_type(Thing3, std::string("Thing3")));
    things_map.insert(ThingsMap::value_type(OtherThing, std::string("OtherThing")));
    return things_map;
}

static std::string ThingEnumToString(ThingEnum thing)
{
    static const ThingsMap things(GetThingsMap());
    ThingsMap::const_iterator it = things.find(thing);
    if (it != things.end()) {
        return it->second;
    } else {
        throw std::invalid_argument("thing");
    }
}
like image 161
Sergey Vyacheslavovich Brunov Avatar answered Dec 19 '25 06:12

Sergey Vyacheslavovich Brunov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!