Let's say I am writing a class that passes a std::variant<A,B> to another class.
While I design the class, I decide I'd like to keep a copy of the last thing that was passed to that other class. Since on startup nothing will have been passed yet, it makes sense to me to store it as a std::optional<std::variant<A,B>>.
But std::monostate exists, and I'm under the impression that it was created to be used specifically in this kind of situation (here with std::variant<std::monostate,A,B>)
The thing is, I can't see why I should use it:
- it seems to me to be less expressive than using
std::optional - I don't want to pass the other function a
std::variant<std::monostate,A,B>(otherwise it'll have to handle the case in which it contains nothing), but as far as I can tell, I cannot assign astd::variant<A,B>object to astd::variant<std::monostate,A,B>variable, so I'd have to manually handle the conversion
So, if not here, when should I use std::monostate instead of std::optional with std::variantand why? Or have I missed something that would make it a good choice here?
std::monostateto your variant never increases its size. Putting the variant instd::optionalalways increases its size.std::monostateis to makestd::variantdefault constructible in case no alternative were.