liveBook · Manning

Has_value

As explained in Learn C++ by Example

has_value is an optional member function that reports whether an optional currently contains a value.

has_value() explicitly checks whether a std::optional currently contains a value. It returns true when the optional is set and false when it is empty, making legitimate absence distinct from a reserved integer. section 3.1.2

Checking optional input

After reading optional numeric input, use if (value.has_value()) before accessing the contained integer. The same presence test can also be written with optional's explicit operator bool, such as while (guess = read_number(std::cin)). section 3.1.2

int actual_value = value.value();

Once has_value() confirms presence, value() retrieves the contained integer; calling value() on an empty optional throws an exception. section 3.1.2

How Learn C++ by Example covers it

How deep it goes
Defines explicit presence checking and contrasts it with operator bool, but does not descend into implementation internals.
Examples
Uses optional integers, a numeric-input function, and a guessing loop that permits giving up.
What it assumes
Assumes basic C++ input and integer handling while introducing std::optional as the mechanism for representing absence.
What you can do after
Apply it via std::optional to distinguish a missing input from a valid integer before accessing the value.
How it connects
Connects has_value() to std::optional, operator bool, value(), and optional numeric input.

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.