User defined type and foreach

Tony tonytdominguez at aol.com
Thu Nov 16 13:24:59 UTC 2017


On Thursday, 16 November 2017 at 12:56:18 UTC, Steven 
Schveighoffer wrote:
> On 11/16/17 3:03 AM, Tony wrote:
>> I made a stack data type and created an opIndex() so it could 
>> be turned into a dynamic array, and created empty() 
>> (unfortunate name), front() and popFront() methods, which I 
>> read allow it to be used with foreach.
>> 
>> However, when I use the class with foreach, the opindex gets 
>> called to create a dynamic array, rather than use the 
>> empty(),front(),popFront() routines. I would prefer it use the 
>> three methods, rather than create a dynamic array.
>
> Remove the opIndex, and see if it works. If it does, then this 
> is a bug. The compiler should try to use the type as a range 
> before seeing if opIndex gives it something.
>
Yes, if I remove opIndex() from the class, doing a foreach loop 
causes popFront(),empty(), and front() to be called and the 
foreach loop works.




More information about the Digitalmars-d-learn mailing list