My take on variant--Jonathan Müller
An interesting point of view and implementation of a variant in one article!
My take on variant
by Jonathan Müller
From the article:
C++17 is going to add std::variant. To quote the linked documentation, it is a “type-safe union”. A union is like a struct, but can only store one member at a time. This has many applications, but sadly it doesn’t mix well with non-trivial types, you have to call the destructor yourself etc. Furthermore, nothing prevents you from accessing a union member that isn’t active.
std::variant fixes that. It correctly calls the destructor when switching the active member, it prevents invalid access, etc. However, I’m not quite happy with it and I needed an implementation now. So I’ve decided to implement my own variant as part of my type_safe library.
It was a fun challenge and since my previous attempt was two years ago, I could improve it a lot. Let’s go through some of my design decisions.