C++ Logo

std-proposals

Advanced search

Re: Initialisers in ternary operators

From: Dvir Yitzchaki <dvirtz_at_[hidden]>
Date: Sun, 13 Sep 2020 12:36:40 +0300
On Sun, 13 Sep 2020 at 11:49, Jorg Brown via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
> OK, so if I only use local control structures, and eschew goto and return,
> then how do I write the typical multiple-error-return flow, without ending
> up with code that is increasingly indented, right up until the end? What's
> the right way, according to your model, of writing:
>
> std::optional<std::string> FindUsersCity(bool non_default) {
> std::optional<std::string> city = std::nullopt;
> std::optional<ContactsServer> contacts =
> GetOrOpenContactsServerConnection();
> if (contacts) {
> std::optional<UserId> uid = contacts->GetUserId();
> if (uid) {
> std::optional<GeoServer> geo =
> GetOrOpenGeoServerConnection();
> if (geo) {
> std::optional<Location> uloc = geo->GetLocation(*uid);
> if (uloc) {
> city = uloc->GetCityName();
> }
> }
> }
> }
> return city;
> }
>

with [P0798] <https://wg21.link/p0798r4> it can be something like:

std::optional<std::string> FindUsersCity(bool non_default) {
  return GetOrOpenContactsServerConnection()
      .transform([](auto&& contacts) { return contacts->GetUserId(); })
      .and_then([](auto&& uid) {
        return GetOrOpenGeoServerConnection().transform(
            [&uid](auto&& geo) { return geo->GetLocation(*uid); });
      })
      .transform([](auto&& uloc) { return uloc->GetCityName(); });
}

Received on 2020-09-13 04:36:53