C++ Logo

std-proposals

Advanced search

Re: [std-proposals] if compiles

From: Jeremy Rifkin <jeremy_at_[hidden]>
Date: Fri, 5 Dec 2025 20:52:48 -0600
Hi,

How often is code written like this? Is this a big enough problem to
warrant a new language feature?

A couple things stand out to me:

1. Generally you want to test specific properties about a type or types in
a requires expression, not an entire if statement body with arbitrary
possible mistakes, potentially unrelated to the types you actually want to
inquire about. This makes the construct inherently bug-prone and could lead
to some potentially very difficult to diagnose situations.
2. Code written as “if compiles { body }” doesn’t strike me as particularly
expressive or nice to read. If statements read as “if condition, do xyz,”
reading “if compiles” leaves me wondering if what compiles? Then what?
3. Would this check all possible ill-formed bodies that don’t compile or
only the ill-formedness that requires expressions check for (i.e. those
pertaining to forming invalid types and or violating semantic constraints
as a reduction of template argument substitution)? If the first, that
strikes me as unimplementable. If the later, the name is misleading.
4. There are constraints on what can go in requires expressions, I don’t
think existing machinery exists for arbitrary if statement bodies.

Cheers,
Jeremy

On Fri, Dec 5, 2025 at 19:51 Frederick Virchanza Gotham via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> It will take me a few more days to finish the paper on 'chimeric_ptr',
> but while writing it, I've come across another problem.
>
> When we use "if constexpr" with "requires", we can end up with code
> like the following:
>
> if constexpr ( requires { p = &static_cast<Interface&>(*q); } )
> {
> p = &static_cast<Interface&>(*q);
> }
>
> The body of the 'if' statement is duplicated in the 'if' condition. We
> could do away with the duplication as follows:
>
> if compiles
> {
> p = &static_cast<Interface&>(*q);
> }
>
> For now, here's one clunky way to avoid the duplication:
>
> #define IF_COMPILES(...) \
> if constexpr (requires { __VA_ARGS__; }) { \
> __VA_ARGS__; \
> }
>
> I had tried experimenting with a lambda as in the following code, but
> it doesn't compile:
>
> auto try_static = [&]<class Dummy = void>() constexpr
> {
> pI = __builtin_addressof(
> chimeric_detail::static_upcast<Interface&>(*p2) );
> };
>
> if constexpr (requires { try_static(); })
> {
> try_static();
> }
>
> The compiler bails out when the body of the lambda fails to compile. I
> thought having the template parameter 'Dummy' would prevent this, but
> alas it doesn't.
>
> I wonder is it at all conceivable that we could have a core language
> feature, "if compiles"?
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2025-12-06 02:53:05