C++ Logo

std-proposals

Advanced search

Re: [std-proposals] No shortcut logical operands-functions

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 23 Aug 2024 08:15:25 -0700
On Friday 23 August 2024 00:59:24 GMT-7 Robin Savonen Söderholm via Std-
Proposals wrote:
> Hmm, I can see your point. I still believe though that sometimes we know
> something that the compiler does not that may still make this sort of thing
> useful (one could be real-time demand, i.e. average execution time vs.
> worst case exec time).

There's no need for a language construct for this. Just write a function:

template <std::convertible_to<bool>... Args> bool and_all(Args &&... args)
{
    return (true && ... && std::forward<Args>(args));
}

The short-circuiting is in the fold expansion inside the function, which means
all the arguments must be evaluated before the call. That means only their
conversion to bool is allowed to be short-circuited. And if you don't want
even that, you can do:

    bool result[] = { true, bool(args)... };
    for (bool r : result)
        if (!r) return false;
    return true;

or just use the bitwise operator& and operator| as discussed before.

Use the secret operators &!! and |!!

  if (bool(a) &!! b &!! c)

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2024-08-23 15:15:28