3 ms·
>Converting string to/from enum It's generally a bad idea to do this, and an enormous headache to even attempt. If you want to do this, maybe you don't want to
by andrepd 9y ago
>Converting string to/from enum
It's generally a bad idea to do this, and an enormous headache to even attempt. If you want to do this, maybe you don't want to use an enum, because that's not what they are for. Maybe you want a hash map instead?
- alkonaut 9y agoWhy is it a bad idea? And if it's a headache, isn't that exactly when the language itself should do it so the developer doesn't have to?
- sidlls 9y agoHow is it a good idea? Not everyone needs this functionality. I wonder how much effort might be required to implement a purely opt-in syntax/library for the purpose: something like Ada's Enumeration_IO.
- alkonaut 9y agoWhen you need it the compiler knows you need it. If you have enum Pet { Cat, Dog } and you write cout<<nameof(Dog) The compiler could just replace it with the string value at compile time. If you have a dynamic one the compiler could just make an array (or worst case hash table lookup) into a static array created at compile time. It's fairly simple and costs nothing if you don't use it. And it's a lot simpler and more elegant to do through the compiler than through a lib, metaprogramming etc. And how useful is it? it's at least useful to be part of how most other languages work these days. An enum is should be seen as a list of names and values. It shouldn't just be limited to be a glorified way of saying const int Cat = 0; const int Dog = 1; Defined like that I'd find it completely unnatural if the symbol names were available at runtime.
- sidlls 9y agoIt has a cost in the size of the object file or executable at least. What if I don't want my data segment being polluted with enum-string-values or, worse, your secret array/hash-table implementation, regardless of how little extra it is? Something like this ought to be opt-in and explicit.
- alkonaut 9y agoIf you use nameof(Cat) then the string "Cat" is included. If you use nameof(some_pet) then the array ["Cat", "Dog"] is included. It's zero cost for something you don't use and it's exactly the same cost as you would have paid by manually adding this.
- sidlls 9y agoAh, right, I see: the compiler only adds these things if it detects that it's necessary (i.e. there must be at least one use). Can't argue with that.
- Koshkin 9y agoUnfortunately, in C++ even the notion of the string type itself is not part of the language...
- stabbles 9y agoIt can be useful for debugging and (de)serialization.
- blt 9y agoMaybe you just want to make an error message from an enum? OK string->enum could get tricky, but enum->string should be straightforward. Please explain why it would be a bad idea.