Search code examples
c++haskellfunctional-programmingc++17stdoptional

Math on std::optionals?


When I try this:

#include <optional>                                                                         using namespace std;                                                                        
int main() {
    return make_optional(2) + make_optional(3);
}                                                                                           

I get this:

error: no match for ‘operator+’ (operand types are ‘std::optional<int>’ and
 ‘std::optional<int>’)
    5 |     return make_optional(2) + make_optional(3);
      |            ~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~
      |                         |                  |
      |                         optional<[...]>    optional<[...]>

It seems natural to add optional types same as size_t types. ~~I know Haskell supports this natively~~ (EDIT: this assumption is not entirely correct). Of course I could write a helper function. My intention of asking is to make sure there is no simpler way to do this. And before you suggest, yes I have googled, RTFM'ed, etc.


Solution

  • As you can see here std::optional simply doesn't offer an operator+ member. After all, std::optional is able to contain anything, including types for which operator+ doesn't make sense. What would optional<that_type>::operator+ do for those types?

    Clearly, you can write your own free function (modulo const/&/both or whatever you deem appropriate for parameters/return type):

    std::optional<int> operator+(std::optional<int> o1, std::optional<int> o2) {
        if (o1) {
            if (o2) {
                return std::make_optional(o1.value() + o2.value());
            }
        }
        return std::nullopt;
    }