1

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?

  • Are you certain this is what your assignment asks you to do? It would be a very unhelpful assignment. Your print_enum function seems to return something. There has to be some sort of miscommunication here. – Captain Giraffe Oct 28 '22 at 01:00
  • @CaptainGiraffe Maybe so, the question was translated between 2 languages and it's possible that I lost the intended meaning of it. – Bl4ck Spyrit Oct 28 '22 at 01:22
  • Related: https://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c11-c14-c17-and-future-c20 – starball Oct 30 '22 at 06:39

1 Answers1

1

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.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • I understand. That means i misunderstood my assignment given by my professor. I should've posted this too. "2. The function below return a variable of type enum. the function receives one parameter which is a string from the ones above ("aplicatieWeb", "aplicatieMobila", etc) and returns the enum value that corresponds to it." – Bl4ck Spyrit Oct 28 '22 at 01:18
  • Can't read that. Edit your question to clarify it. – Marcus Müller Oct 28 '22 at 01:19
  • 1
    @Bl4ckSpyrit using a `std::unordered_map` would easily solve that task. – Remy Lebeau Oct 28 '22 at 01:58
  • 1
    Yep, exactly. I mean, you've been pointed at std::unordered_map. Maybe check it out on cppreference.com, @Bl4ckSpyrit! – Marcus Müller Oct 28 '22 at 02:02