C++ Logo

std-proposals

Advanced search

[std-proposals] Patter matching P2688r3, P2392r3 and more

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Sat, 26 Oct 2024 15:05:28 +0200
As I see there are a couple of competing proposals that try to solve
the same problem.
What is the committee option on the preferred version of it?

For me in some way better is Herb's one that adds two operators `as` and `is`.
As this is a more general solution that is used in many other contexts.
But `match` operator unique features look interesting too.

If we combine some elements from booths we could get some interesting results:

```
#define TRY_OR_RETURN(RET) match { is void => return (RET); is _ b => *b; }
#define THEN(FUNC) match { is _ b => FUNC(b); }

auto foo(auto a)
{
    auto p1 = process1(a) TRY_OR_RETURN( fallback1() );
    auto p2 = process2(p1) TRY_OR_RETURN( fallback2() );
    auto p3 = process2(p2) TRY_OR_RETURN( fallback3() );
    return p3;
}

//or more compressed:
auto foo(auto a)
{
   return a
       THEN(process1)
       TRY_OR_RETURN( fallback1() )
       THEN(process2)
       TRY_OR_RETURN( fallback2() )
       THEN(process3)
       TRY_OR_RETURN( fallback3() );
}
```

Thanks to `is void` this code can work for all types like
`std::optional`, `T*`, smart pointers, `std::expected` or any user
defined type that handles `operator is<void>`.

This somehow look like a pipe operator too thanks to that it avoiding
introducing local variables.

compare this to current code:

```
auto foo(auto a)
{
    auto p1 = process1(a);
    if (p1)
    {
        return fallback1();
    }
    auto p2 = process2(*p1);
    if (p2)
    {
        return fallback2();
    }
    auto p3 = process2(*p2);
    if (p3)
    {
        return fallback3();
    }
    return *p3;
}
```

We have more boilerplate and easier to forget adding checks.


Overall I look forward to what version of pattenrmancih will be choosed.

Received on 2024-10-26 13:05:41