Date: Wed, 3 Sep 2025 09:03:05 +0200
On 03/09/2025 01:02, Bjorn Reese via Std-Proposals wrote:
> On 9/2/25 23:59, Sebastian Wittmeier via Std-Proposals wrote:
>
>> There is lots of complex code out there using those implicit
>> conversions from bool to 0 and 1.
> Which is particularly useful in generic branch-free programming that
> works for both scalar and SIMD types. For example
>
> template <typename T>
> T sgn(T x) {
> return (x >= T(0) - (x <= T(0));
> }
>
> template <typename T>
> T max0(T x) {
> // max(0, x)
> return x * (x > T(0));
> }
>
> While SIMD relational operations return a mask, it serves the same
> purpose as a bool in the scalar case.
>
While code like that /uses/ implicit bool-to-int conversions, having
those conversions be implicit is not at all necessary. If the
conversions were not implicit, you'd simply write :
return int(x >= T(0) - int(x <= T(0));
instead.
The prime reason for having implicit conversions is that C had
comparison operators that evaluate to int from before "bool" was
introduced in C++. Backwards compatibility rules.
> On 9/2/25 23:59, Sebastian Wittmeier via Std-Proposals wrote:
>
>> There is lots of complex code out there using those implicit
>> conversions from bool to 0 and 1.
> Which is particularly useful in generic branch-free programming that
> works for both scalar and SIMD types. For example
>
> template <typename T>
> T sgn(T x) {
> return (x >= T(0) - (x <= T(0));
> }
>
> template <typename T>
> T max0(T x) {
> // max(0, x)
> return x * (x > T(0));
> }
>
> While SIMD relational operations return a mask, it serves the same
> purpose as a bool in the scalar case.
>
While code like that /uses/ implicit bool-to-int conversions, having
those conversions be implicit is not at all necessary. If the
conversions were not implicit, you'd simply write :
return int(x >= T(0) - int(x <= T(0));
instead.
The prime reason for having implicit conversions is that C had
comparison operators that evaluate to int from before "bool" was
introduced in C++. Backwards compatibility rules.
Received on 2025-09-03 07:03:11