1. 11
  1.  

  2. 3

    One problem with std::optional, at least at the moment, while it’s relatively new, is that std is opinionated, so you often won’t find library functions that work with a std::optional-based codebase.

    For example, parsing an integer from a string is a classic example of a function which might not succeed. So it would make sense to use std::optional to store the result. However, the standard library provides int stoi(const std::string& str, std::size_t* pos = 0, int base = 10) and friends, which signal failure by throwing exceptions.

    So, in theory, std::optional provides an alternative way to handle failure, somewhat like some haskell or rust code might, making the possibility of failure explicit in the type, and thus forcing you to explicitly handle it or pass it on. However, (unless a library exists which I’m not aware of?) you may need to reimplement large parts of the standard library to make them fit.

    1. 3

      Right. “This is a feature of the standard library!” means something entirely different in C++ than in other programming languages.

      1. 2

        Can you make it much less of a headache by defining a generic function that takes a lambda, calls it in a try/catch, returns the successful value from the try branch, returns nullopt from the catch?

        1. 1

          There are any number of workarounds, that obfuscate the code to varying degrees. This same situation arose with Optional in java 8, it’s there, but not really, so a lot of places you’d like to use it you have to go through similar contortions. The other problem is if interacting with different teams writing different parts of the app; everyone has to be on the same page or you’ll end up wrapping/unwrapping optional all over. And libraries. In the end I found optionals were a lot of trouble for very little gain.

          1. 1

            I did wonder about that. However, blindly catching all different exceptions and effectively discarding the information about which exception it was seems unwise. Of course you could keep the information while still using sum types, but then you don’t really want std::optional, you want an either type which can hold either a valid value or an error code. I’m not sure whether the standard library has one of these or whether you’d have to roll your own.

            1. 1

              blindly catching all different exceptions and effectively discarding the information about which exception it was seems unwise

              Sure, I wouldn’t be very happy with a blind try/catch around something like a database access or RPC call. Just if the thing you’re wrapping is something really boring like (say) parsing a string into an integer, the exception if it goes wrong isn’t going to be very interesting anyway.