opApply ref and "const" iterators

Denis Koroskin 2korden at gmail.com
Mon Sep 28 17:31:00 PDT 2009


On Tue, 29 Sep 2009 02:58:01 +0400, gzp <galap at freemail.hu> wrote:

> Hello,
>
> Iám new to D so i might be all wrong. Given the code:
>

Hello and welcome to the D world!

> class Foo {
> 	int opApply( int delegate(ref real) dg ) {...} //A.
> 	int opApply( int delegate(real) dg ) {...} // B,
> }
>
> ...
> 	Foo foo = new Foo;
> 	foreach( a; foo ) {...}  // 1.
> 	foreach( ref a; foo ) {...} // 2,
>
> Is it normal that, the A. version (with ref) is called for both cases

I believe questions like this belong to D.learn newsgroup.
I always wondered why is it so, too, but I never thought as being a bug  
about it.
Perhaps, someone else may explain a reason behind it. You may create a  
bugzilla ticket if no one will give an answer.

> and if the A is eliminated, only the 2. foreach loop will compile ?

I believe none of them will compile.

> The second case works as i expected but what about the first case - the  
> B. function won't be called ever ?
>
> Furthermore, i wanted to create a const iterator
>
> class Foo {
> 	int opApply( int delegate(ref real) dg ) {...} //A.
> 	const int opApply( int delegate(real) dg ) {...} // B,
> }
>
> ...
> 	Foo foo = new Foo;
>         const Foo f2 = foo;
> 	foreach( a; f2 ) {...}  // 1.
> 	foreach( ref a; foo ) {...} // 2,
>
> It won't compile. (dmd 2.032) (I expected that, for the 1. loop the B  
> version and for the 2. loop the A version of the functions'd  be called)
>
> So what is the D way to create const iterator ?

Once again, a ref version (A) is called, which is not marked as const and  
as such your code doesn't compile. Try marking it const, too, and it will  
pass.



More information about the Digitalmars-d mailing list