7

How can I return a value, similar to null, with std::optional? My function receives an int index as parameter to iterate through a list, if the index value is not valid, how this std::optional can be used to return a value similar to null?

Porton_
  • 113
  • 1
  • 5
  • 9
    `return {};` doesn't work for you? – Zoso Aug 17 '21 at 18:26
  • 1
    That's pretty much the whole point of `optional`. So I'm not quite sure what you're asking. – Mat Aug 17 '21 at 18:27
  • If `std::optional` doesn't quite fit your use case (which isn't described in detail), you might consider using `std::variant` with `std::monostate` as one of the variant types. – Eljay Aug 17 '21 at 18:34

1 Answers1

16

nullptr is to pointers what std::nullopt is to std::optional.

eerorika
  • 232,697
  • 12
  • 197
  • 326