To return an optional result from a function, we can use std::optional class template as type (C++17) as shown below:

#include <iostream>
#include <optional>
 
std::optional<int> getValue(bool shouldGet)
{
    if (shouldGet)
    {
        return 5;
    }
 
    return {};
}
 
int main(int argc, char const *argv[])
{
    std::optional<int> result{getValue(true)};
    if (result)
    {
        std::cout << *result << "\n";
    }
 
    result = getValue(false);
 
    if (!result)
    {
        std::cout << "Optional result has no value\n";
    }
 
    return 0;
}
 

std::optional is defined in header file optional. std::optional can be implicitly converted to boolean similar to pointers to check if it has a value or not. Another way is to use method .has_value().

To get the value from std::optional, we can dereference it like pointer or use .value() method.

References

  1. https://www.learncpp.com/cpp-tutorial/stdoptional/