#cplusplis
Explore tagged Tumblr posts
Text
C++ Tips: std::optional<T>
std::optional<T> is a class defined in <optional>. It is added in C++17 and it presents a variable that may have a value. The value is optional, so the name.
There are 2 ways to make a std::optional
You will use 6 functions when you work with std::optional 90% of the time.
std::optional() //the constructor
std::make_optional() //make std::optional
has_value() //true if it has a value, otherwise false
value() //get the value of optional
value_or() //get the value of optional but if the optional doesn't contain one, it returns another value from the arguments
reset() //reset / destroy the contained value
Generally, std::make_optional is the way to go for creating objects unless you don't want to have a value contained when initializing.
3 notes
·
View notes