Issue with opApply and const

Steven Schveighoffer schveiguy at yahoo.com
Tue Nov 4 07:31:55 PST 2008


While porting Tango to D2 I ran into this issue.

When applying const tags to BitArray, I've found that opApply has two 
issues.

I have to at least double the number of opApply functions.  The variations 
are for const or not, and using an index or not.

So I now have 4 opApplys with the following signatures:

int opApply( int delegate(ref bool) dg )
int opApply( int delegate(ref size_t, ref bool) dg )
int opApply( int delegate(ref const(bool)) dg ) const
int opApply( int delegate(ref size_t, ref const(bool)) dg ) const

So first issue, it sucks that I have to put ref on the size_t (index). 
Builtin arrays don't permit this, so it makes no sense why the compiler 
can't figure out whether a ref parameter is allowed in the foreach loop by 
looking at the opApply signature.  I should be able to compile with:

int opApply( int delegate(size_t, ref bool) dg )

And furthermore, to save extra code and headache, I should be able to remove 
ref altogether when the struct is const:

int opApply( int delegate(size_t, bool) dg ) const

---------------------

Second issue, I get a compile error with the following unittest code:

        BitArray a = [1,0,1];

        int i;
        foreach( b; a )
        {
            switch( i )
            {
            case 0: assert( b == true );  break;
            case 1: assert( b == false ); break;
            case 2: assert( b == true );  break;
            default: assert( false );
            }
            i++;
        }

tango/core/BitArray.d(414): Error: cannot uniquely infer foreach argument 
types

WTF?  How am I supposed to make const-correct structs/classes that allow 
setting elements during foreach when the struct/class is not const?

Is this a bug, or is there another way to do this?

I know Walter is working on updating foreach so that it works with ranges, 
will fixes to these problems also be included in that update?

-Steve







More information about the Digitalmars-d mailing list