the trait youre looking for is __traits(isRef, data). with an auto ref parameter you can do the whole thing in one function instead of the compiles trick:

```d
auto asBits(D)(auto ref D data)
{
    static if (__traits(isRef, data) && isMutable!D)
        return BitsRefSlice!D(&data, 0, D.sizeof * 8);
    else
        return BitsValSlice!D(data, 0, D.sizeof * 8);
}
```

isRef tells you whether the argument actually bound by reference, so immutable lvalues and rvalues fall through to the by-value branch naturally. isMutable is from std.traits. one caveat: the by-value branch has to copy the data before slicing, since an rvalue is gone by the time the expression ends.

On Monday, 14 September 2026 at 11:02:49 UTC, realhet wrote:
On Monday, 14 September 2026 at 10:51:38 UTC, realhet wrote:
Hi! I try to make the easiest syntax for manipulating bits.

Update: This way I it works, but I think I'm abusing it.

```d
auto asBits(D)(ref D data)
{
static if(__traits(compiles, data = data)) return BitsRefSlice!D(&data, 0, D.sizeof*8);
        else    return BitsValSlice!D(data, 0, D.sizeof*8);
}
auto asBits(D)(D data)
=> BitsValSlice!D(data, 0, D.sizeof*8);
```

Somebody please tell me what's the best practice for this.

Reply via email to