Search code examples
c++enumerate

Check if string contains Enum Value C++


I am trying to solve an assignment and I searched in every possible way for an answer, but managed to only get "how to transform an enum into a string"

I have a string called type that can only contain "webApp", "MobileApp" and "DesktopApp". I have an enum that looks like this:

enum applicationType { webApp = 5, MobileApp = 10, DesktopApp = 15 };

How can I print the value from the enum corresponding to the string using a function?


applicationType print_enum(string tip) {
    //if tip contains "webApp" i should print 5
}

How do I make the function test if the value of the string corresponds to a value in the enum, and if it does print that value?


Solution

  • You simply can't.

    The names of c++ objects, types and enum entries are not available as strings. They're effectively just placeholders, identifiers for things the compiler needs to identify. It discards these identifiers pretty early on the way from source code to machine code.

    (As of c++20. Who knows what the future brings.)

    If you need to do that, it's necessary to replicate your enum, e.g. as std::unordered_map<applicationType, std::string>.

    If you just need to look up a string based on an integer, just use int instead of an enum type as key in the map, and forget about the enum.