On Wednesday, 7 July 2021 at 16:20:29 UTC, realhet wrote:
Hi,
I wanted to make a container class that exposes its elements
using a simple "alias this", but getting weird errors:
I test with the std.algorithm.filter template function.
1. when I use "alias this" on a function that returns a slice,
making the internal array unreachable, filter just can't
compile.
2. when I expose the array as it is, filter deletes the array
after it returns.
My goal is to make a class, which acts like an array, but also
having member functions to add/remove/find its items. On top of
that this class has an owner (a database table thing) too.
In general, it is not a good idea to have your container class
also function as a range, for exactly this reason. Instead, your
container class should have a method that returns a range over
its elements, with the range being a separate object.
The conventional way to do this is to overload `opIndex`:
```d
class C
{
private int[] array;
this(int[] array) { this.array = array; }
int[] opIndex() { return array; }
// etc.
}
void main()
{
import std.algorithm;
auto c = new C([1, 2, 3]);
c[].filter!"true".each!writeln;
assert(c[].length == 3);
}
```