C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::unreachable<T>()

From: Alejandro Colomar <une+cxx_std-proposals_at_[hidden]>
Date: Thu, 21 May 2026 23:34:35 +0200
Hi Jonathan,

On 2026-05-21T22:02:25+0100, Jonathan Grant via Std-Proposals wrote:
>
>
> On 21/05/2026 13:32, Mital Ashok via Std-Proposals wrote:
> > This should be a non-breaking extension.
> > Add a templated function:
> >
> > template<class T>
> > [[noreturn]] T unreachable() {
> > unreachable();
> > }
> >
> > This is useful in ternary conditional expressions, like `o.is_valid()
> > ? *o : std::unreachable<O::value_type>()`.
> >
> > It can also be used in some weird cases where you want to ODR-use
> > std::declval in a constant expression (e.g., when used as an unknown
> > reference)
> >
> > T is returned instead of add_rvalue_reference_t<T> intentionally
> > because of the use case in conditional expressions where we don't want
> > to materialise a temporary the other side (so std::unreachable<int>()
> > is a prvalue for example). This deviates from std::declval but has
> > similar semantics to std::reference_con{struct,vert}s_from_temporary
> > (T is prvalue, T& is lvalue, T&& is xvalue), with the unfortunate
> > exclusion of array types, but that should not be a big use case.
> >
> > The above is one of the things that can be discussed about this
> > facility. I was mostly wondering if there is anything else I need to
> > consider before writing R0 of the proposal
>
> Are you using this to reduce the binary size on an embedded platform?
>
> I don't use __builtin_unreachable(), but I would if the compiler's control-flow analysis would warn that actually it is reachable! That would be really useful, could be maybe used by P4021 compile_assert(). Sharing what each vendor's compiler knows is very helpful.
>
> myfunc(2);
>
>
> int myfunc(int x)
> {
> if (x == 0)
> return 1;
>
> __builtin_unreachable();
> }

That ship has sailed for unreachable(), I fear. While I would have
liked unreachable() to be that tool, I don't think we can do that now.

But we could add a new tool, a 'trap' statement, that would be diagnosed
if it is not optimized out (maybe as recommended practice).

 trap; // diagnosed unless proved unreachable.


Have a lovely night!
Alex

-- 
<https://www.alejandro-colomar.es>

Received on 2026-05-21 21:34:44