===={} ou std::nullopt====
C'est la même chose.
#include
#include
struct Version {
Version() {}
uint32_t major = 0;
uint32_t minor = 0;
uint32_t patch = 0;
};
int main() {
std::optional o1 = {};
std::optional o2 = 1;
std::optional o3 = {};
std::optional o4 = {{}};
assert(!o1);
assert(o2);
assert(!o3);
assert(o4);
}
[[https://stackoverflow.com/questions/57964217/stdoptional-construct-empty-with-or-stdnullopt|std::optional - construct empty with {} or std::nullopt?]] {{ :lang:cpp:optional:c_-_std_optional_-_construct_empty_with_or_std_nullopt_-_stack_overflow_01_02_2023_11_59_46_.html |Archive du 16/09/2019 le 01/02/2023}}
====std::make_optional====
''std::make_optional'' force la création d'un optional alors que std::optional peut copier un optional.
#include
#include
int main()
{
auto inner=std::make_optional(325);
auto opt2=std::make_optional(inner); // makes std::optional>
auto opt3=std::optional(inner); // just a copy of inner
static_assert(std::is_same_v>>);
static_assert(std::is_same_v>);
}
[[https://stackoverflow.com/questions/62734897/what-is-the-point-of-stdmake-optional|What is the point of `std::make_optional`]] {{ :lang:cpp:optional:c_-_what_is_the_point_of_std_make_optional_-_stack_overflow_14_03_2023_12_26_26_.html |Archive du 04/07/2020 le 14/03/2023}}
====Spécificités====
===Opérateur ternaire===
Il faut spécifier explicitement l'optional.
std::optional t;
t = true ? 1 : std::optional{std::nullopt};