const version for foreach/opApply
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jun 25 08:35:08 PDT 2012
On Fri, 08 Jun 2012 12:33:20 -0400, Matthias Walter
<xammy at xammy.homelinux.net> wrote:
> Hi,
>
> trying to traverse the entries of a std.bitmanip.BitArray I stumbled
> upon the following problem:
>
> The original code is as follows:
>
> int opApply(scope int delegate(ref bool) dg)
> {
> int result;
> for (size_t i = 0; i < len; i++)
> {
> bool b = opIndex(i);
> result = dg(b);
> this[i] = b;
> if (result)
> break;
> }
> return result;
> }
>
> In case I want to accept const(BitArray) objects, it shall look like the
> following (maybe using "ref const(bool)" for the delegate parameter?):
>
> int opApply(scope int delegate(bool) dg) const
> {
> int result;
> for (size_t i = 0; i < len; i++)
> {
> bool b = opIndex(i);
> result = dg(b);
> if (result)
> break;
> }
> return result;
> }
>
> Can one glue both things together into a single routine (using inout
> magic or whatever)?
Not currently, because we have an issue of inout having two different
meanings.
When a function's parameters or return values are adorned with inout,
inout becomes sort of a wildcard.
When inside a function, however, inout turns into a restrictive form of
const.
But what happens with a delegate parameter that *takes* an inout
parameter? For example:
int opApply(scope int delegate(ref inout(bool)) dg) inout
Is inout(bool) a wildcard for the delegate? Or is part of the inout
wildcard of the entire function? Inside opApply, should it be the
restrictive const type?
Currently, it is a wildcard for the delegate, and so it doesn't really
help, once you go into opApply, you can't temporarily remove the inout
type.
Note that for your particular instance I'd *recommend* two different
versions, since the const version can be vastly optimized (passing a bool
by value vs. by reference is much more efficient, and then there is no
need to re-store the value after the delegate).
There are quite a few ideas being floated around as to how to make inout
work for opApply, but for now, you should avoid it.
-Steve
More information about the Digitalmars-d-learn
mailing list