I have:
Foo foo = new Foo();
foreach (i; 0..10)
{
Bar bar = foo.getBar(i);
...
}
I want to be able to instead say (equivalently):
foreach (bar; foo.getAllBars())
{
...
}
How do I go about implementing getAllBars()
?
I figured something like this:
class Foo
{
auto getAllBars()
{
return map!(getBar)(iota(10));
}
}
But you can't do that of course because getBar
depends on the this
parameter, which will go out of scope. The same applies if you try to create a local function
or delegate
. I also considered creating a function object with opCall
, but you can't use those with map
(can you?).
Some requirements:
- The returned range must be lazy (so no copying it into an array first)
- Assume that
getBar
is the only way to get at the data. - I want the map to be encapsulated by the class (i.e. no moving the map to the call site).