4 ms·
> C++ needs an actual sum type, and variant isn’t it. Sorry. Don't disagree at all, but in the meantime I'd still avoid union and use variant instead but wrapp
by kllrnohj 4y ago
> C++ needs an actual sum type, and variant isn’t it. Sorry.
Don't disagree at all, but in the meantime I'd still avoid union and use variant instead but wrapped in a class that exposes named accessors. You don't have to actually expose the orderings of a variant to anything that way.
It's a bunch of annoying boilerplate to be sure, though. If the metaclasses proposal ever happens then it could be generated which would be cool.
- amluto 4y agoThis is yet another step on the slippery slope toward extremely slow compilation. I once timed this little program: #include <boost/variant.hpp> on a machine that was very fast for its time. It took seven seconds to compile! Now modern variadic templates are quite an improvement, but not enough of one. A metaclass generating an instantiation of an n-element variant which, in turn, instantiates the n-1 element tail, etc is quite a log of generated code and types, and anything using it needs to contend with all that complexity to resolve method calls, etc. In contrast, any language with native sum types can handle this efficiently. Furthermore, native sum types make it obvious to the compiler, type checker, static analyzers, etc that the type in question is actually a sum type. Getting a compiler to understand a metaclass-based variant well enough to do something like Rust’s sentinel value optimizations sounds miserable.