Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ when should we use std::any, std::variant or std::optional? [closed]

Tags:

c++

I know there is a question about std::any vs std::variant, but std::optional is also about a same thing. C++ std::variant vs std::any

like image 397
christo Avatar asked Oct 22 '20 10:10

christo


People also ask

What is the point of std :: variant?

The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).

What is the use of std :: optional?

std::optional contains the object within itself, depending on where it is stored (stack/data/heap) std::optional makes a copy of the contained object. Monadic functions will be added in C++23 to improve the abstraction in our code by removing the needs of writing boilerplate code.

What is std :: optional C++?

(since C++17) The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.

What is std :: any?

The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.


1 Answers

I have a very general rule:

Every time you want to use a union use std::variant.

Every time you want to use a void* use std::any.

Every time you want to return nullptr as an indication of an error use std::optional.

like image 141
Vasilij Avatar answered Sep 24 '22 03:09

Vasilij