4 ms·
At the risk of stating the obvious -- in C and C++, unions solve that problem.
by chubot 10y ago
At the risk of stating the obvious -- in C and C++, unions solve that problem.
- catnaroek 10y agoYou still need to roll your own tagged unions by hand. Algebraic data types solve that problem.
- metaobject 10y agoBut can you have a union of string and numeric data? It's been awhile since I've used them, but how would that work?
- ruste 10y agoUnion of numeric and character pointer.
- wcrichton 10y agoThey 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.
- wolfgke 10y agoReplace the type (e.g. std::string) by the pointer type (e.g. std::string*) in the union.
- flamedoge 10y agounion is a max-size-fits-all solution. a better solution is inheritance.
- clappski 10y agoWhich 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.
- beached_whale 10y agoGenerally 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)