Re:Programming Your Own Language in C++
by chubot on Monday August 08, 2016 @12:30AM
(#12245506)
At the risk of stating the obvious -- in C and C++, unions solve that problem.
[ Parent
| on HN ]
They solve the memory issue, although they are inconvenient to use vs. pattern matching and aren't type safe. Additionally, I've had no luck using classes (e.g. string) inside of unions because the compiler reasonably complains about initializers. I believe this is somewhat solved with boost::variant (and that's also getting put into C++17, iirc), but ideally it would be a part of the type system.
Replace the type (e.g. std::string) by the pointer type (e.g. std::string*) in the union.
Re:Programming Your Own Language in C++
by metaobject on Monday August 08, 2016 @12:59AM
(#12245593)
But can you have a union of string and numeric data? It's been awhile since I've used them, but how would that work?
Union of numeric and character pointer.
You still need to roll your own tagged unions by hand. Algebraic data types solve that problem.
union is a max-size-fits-all solution. a better solution is inheritance.
Which would introduce the overhead of a vtable, which would vary depending on how deep your inheritance goes. I haven't read the article, but I would maybe use an enum if this is just use to parse variable declarations.
Re:Programming Your Own Language in C++
by beached_whale on Sunday August 14, 2016 @09:24PM
(#12288102)
Generally the vtable is not much slower. I believe around the cost of an extra pointer derefence vs the alternative of branching. Also the compiler can sometimes optimize the cost to be the same as a normal call(e.g. final)