Hacker News new | ask | show | jobs
by logicchains 3549 days ago
Note C++2017's std::variant is based upon boost::variant, which has been around since at least 2004 (http://www.boost.org/doc/libs/1_31_0/doc/html/variant.html, http://www.boost.org/users/history/).

boost::variant however lacks a nice visit method that takes lambdas, instead requiring the user to create visitor classes. This verbosity may be part of the reason it wasn't adopted in mass, in spite of its advantages in terms of type safety.

1 comments

They are implemented completely differently. The only real similarity is in the name and API. Boost variant suffers from significant performance penalties that the new std::variant does not have.
If you look at http://www.boost.org/doc/libs/1_62_0/doc/html/variant/design..., Boost variant has no performance penalty due to backup storage if any of its bounded type is nothrow default-constructible. In practice, you just need a single nothrow default-constructible type in boost::variant to satisfy that requirement. This can be `int` or `boost::blank`. And that's that - no performance penalty.
> Boost variant has no performance penalty...

I have a big project that uses boost::variant. The runtime performance may be fine, but I swear that just compiling the header took about 5 seconds.

Pre-C++-11 fake variadic templates are just painful.

(IMHO two of the major missing features in Rust that are really need are integer generics and varidic generics. Without integer generics, arrays over 32 elements don't work correctly, and that's really annoying sometimes.)

Boost.variant suffers for being correct by default (i.e. strongly exception safe) plus opt-in for speed, while the new std::variant can get in an invalid state if an exception is thrown at a bad time. Let's say that the trade-offs will be hotly debated until the standard actually ships.
The problem with Boost.variant is that all data is doubly allocated, including at least 1 heap allocation as a copy. This is not obvious and is certainly not what a lot of users would want. But you are right, it does this to avoid exceptional situations.
The tradeoffs have been hotly debated for years :) The current spec is finally something the committee could agree on, after countless proposals, counter-proposals, endless email discussions and long evenings at committee meetings.
I agree that the current spec is better than none at all, but it feels like a bad compromise. I would have preferred either a fully exception safe variant or one with an explicit empty state.