std::optional example

std::optional is a way of handling values in C++ where it is not clear if there actually will be a value: it represents an object that may have a value.

std::optional<std::string> value;

std::optional is in C++ since C++17 and adds to readability of code, as it explicitly expresses its intention.

How to use it

void updateProfile(uint64_t handle, std::optional<std::string> name) {
    if (name) {
        std::cout << name.value() << std::endl;
    }
}
updateProfile(12345, "Ernie");
// avoid making a copy:
std::string name{"Ernie"};
updateProfile(12345, 
    std::make_optional<std::string>(std::move(name)));

If you don’t want to call it with a name, you can do:

updateProfile(12345, {});

or

updateProfile(12345, std::nullopt);

Improved readability

No need for an extra if() or ternary : ? statement, if name has no value, value_or() returns the alternative.

name.value_or("no name set");

The * and -> operators can be used to access the value, e.g.:

std::cout << *name << " " << name->size() << std::endl;