Re:Ill-Advised C++ Rant, Part 2 (2016)
by alkonaut on Wednesday October 25, 2017 @03:58PM
(#15553572)
Why 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?
[ Parent
| on HN ]
How 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.
Re:Ill-Advised C++ Rant, Part 2 (2016)
by alkonaut on Wednesday October 25, 2017 @06:16PM
(#15554780)
When 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.It 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.
Re:Ill-Advised C++ Rant, Part 2 (2016)
by alkonaut on Thursday October 26, 2017 @01:29AM
(#15556580)
If 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.
Ah, 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.