0

I am trying to return an enum based on a string value (the string is from a json file, if it matters) Basically, where in code I would write enumName::MyName, I want to be able to have something like

std::string name = "MyName";
return enumName::name; // this gets converted to enumName::MyName

Obviously that's incorrect syntax. I had the idea of using macros to solve my problem, so here's my current attempt:

#define stringToName(n) enumName::##n

Where I used the ## token pasting operator. But in that case, n isn't evaluated before being copied, so the following thing happens

return stringToName("MyName");
//which becomes
return enumName::"MyName";

Or

std::string name = "MyName";
return stringToName(name);
//which becomes
return enumName::name;

And that's not quite what I want. Is there a way to make it work? (Ideally without having to write each and every enum name manually in a dictionary or something like that)

aradarbel10
  • 435
  • 3
  • 10
  • 1
    [The Toggle that Wouldn't](https://thedailywtf.com/articles/The-Toggle-that-Wouldnt) – Joseph Sible-Reinstate Monica Jul 01 '21 at 03:06
  • No way to do it at compile time - a string doesn't contain a value until run time. – Mark Ransom Jul 01 '21 at 03:07
  • @MarkRansom I do need it to happen at run time (when the json is being read). but now that I think about it macros would help only when compiling wouldn't they? so my idea is pretty useless. – aradarbel10 Jul 01 '21 at 03:09
  • 1
    If the language can't do what you need, reconsider what you need. – Mark Ransom Jul 01 '21 at 03:10
  • Check out https://stackoverflow.com/q/7163069/5987 if you want to do it at runtime. – Mark Ransom Jul 01 '21 at 03:12
  • This feels like an [XY Problem](https://xyproblem.info/), what do you think you need this functionality for? There is probably a much simpler solution. – Fantastic Mr Fox Jul 01 '21 at 03:12
  • @FantasticMrFox well, I am working with a third-party library (SFML) and trying to import some keyboard keys from a json. SFML saves those as a very convenient enum which allows me to do some ascii manipulation to get the corresponding enum value of letters, but that won't work if I want to use other keys like numpad, control key codes, things like that. – aradarbel10 Jul 01 '21 at 03:20
  • Has someone already mentioned this: https://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c11-c14-c17-and-future-c20 – Jerry Jeremiah Jul 01 '21 at 03:42
  • Related to [opposite-of-c-preprocessor-stringification](https://stackoverflow.com/questions/6982179/opposite-of-c-preprocessor-stringification). – Jarod42 Jul 01 '21 at 09:30

1 Answers1

0

At last, I found a solution using the magic_enum library that was mentioned in a question linked by Jerry. I don't understand exactly how/why it works yet, but it's clean and does the job.

aradarbel10
  • 435
  • 3
  • 10