News for hackers. Stuff that matters.
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.
Re:Programming Your Own Language in C++ by wcrichton on Monday August 08, 2016 @01:03AM (#12245601)
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.
Re:Programming Your Own Language in C++ by wolfgke on Monday August 08, 2016 @06:40AM (#12246682)
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?
Re:Programming Your Own Language in C++ by ruste on Monday August 08, 2016 @12:55PM (#12249155)
Union of numeric and character pointer.
Re:Programming Your Own Language in C++ by catnaroek on Monday August 08, 2016 @12:51AM (#12245574)
You still need to roll your own tagged unions by hand. Algebraic data types solve that problem.
Re:Programming Your Own Language in C++ by flamedoge on Monday August 08, 2016 @02:39AM (#12245829)
union is a max-size-fits-all solution. a better solution is inheritance.
Re:Programming Your Own Language in C++ by clappski on Monday August 08, 2016 @04:04AM (#12246143)
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)