foreach over pointer to range
Artur Skawina
art.08.09 at gmail.com
Tue Jun 5 13:38:22 PDT 2012
On 06/05/12 22:23, simendsjo wrote:
> On Tue, 05 Jun 2012 20:46:51 +0200, Timon Gehr <timon.gehr at gmx.ch> wrote:
>
>>
>> It should be dropped. A pointer to range is a perfectly fine range.
>
>
> Sure..? I couldn't get it to work either:
> struct R {
> string test = "aoeu";
> @property front() { return test[0]; }
> @property bool empty() { return !test.length; }
> void popFront(){test = test[0..$];}
> }
>
> void main() {
> R r;
> R* p = &r;
> foreach(ch; p) // invalid foreach aggregate p
> writeln(ch);
> }
It /is/ a valid range, but it's /not/ currently accepted
by foreach.
So you have to write the above as:
struct R {
string test = "aoeu";
@property front() { return test[0]; }
@property bool empty() { return !test.length; }
void popFront(){test = test[0..$];}
}
struct RangePtr(R) {
R* ptr;
alias ptr this;
@property front()() { return ptr.front; }
}
void main() {
R r;
auto p = RangePtr!R(&r);
foreach(ch; p)
writeln(ch);
}
which works, but only obfuscates the code and can be less efficient.
artur
More information about the Digitalmars-d
mailing list