On Sun, 13 May 2018 06:03:24 GMT
[snip]
> >> std::any is variant, and std::optional would better be replaced by future
> >> addition of tagged unions as in Rust eg ADT's in functional languages.
> >> They started with decomposition of tuples, next are tagged unions ;)
> >
> > C++ already has discriminated unions (aka sum types). It's called
> > std::variant.
>
> It's not built in into the language so you need std::optional,std::any
> ... ;)
> Anyway, what is difference between std::any and std::variant?
std::variant, std::optional and std::any are all provided in the
standard library for C++17, so I am not clear what you mean that
std::variant is 'not built in into the language so you need
std::optional, std::any ...'.
std::variant is a perfectly normal sum type or discriminated union.
There is nothing much more to be said about it, except that pattern
matching on it is possible using function overloading with std::visit
but is inconvenient. std::optional is a normal Maybe or Option type.
std::any is somewhat odd. It seems to be a means of introducing
dynamic typing to C++ of the python/javascript/lisp kind, and as such I
can see it could have its uses: in particular, it does enable you to
have heterogenous C++ containers. It has a type operator which returns
a std::type_info object describing its contents, and an any_cast access
operator which throws an exception if the typeid of the contained
object is not the type requested by the cast; so to that extent it is a
safer version of void* with type introspection.
I don't use any of these because I write code which depends on C++11/14
but not C++17. From C++11 it is not that difficult to construct
discriminated (tagged) unions yourself, and I have my own home-grown
option class.
Chris