Is it possible to return mutable and const range from a single method?
realhet
real_het at hotmail.com
Mon Aug 22 23:46:03 UTC 2022
On Monday, 22 August 2022 at 19:35:11 UTC, Steven Schveighoffer
wrote:
> It is possible to write the same function for both const and
> mutable overloads by using the `this` template parameter:
I guess before the "inout", "this This" was the only way to do
this. I must remember this, it's really usefull.
I also had lack of knowledge about that is(T==const) expression
that Ali mentioned.
In my program, I passed isConst as a template parameter with
default initialization. It only needed one static if, where the
range returns the front.
Thank You all!
- descendant classes can have parent or not (overload getParent)
- allParents, thisAndAllParents: optionally enumerates this
before the parents.
- it can also filter the class type allParents!CustomContainer
- supports const.
It's much better than the previous
visitor_function_with_a_callback_function_that_returns_false_when_it_wants_to_stop thing.
I really beleive that in the end it generates only a while loop
that the compiler can optimize well. (Unlike recursion or
callbacks)
```d
inout(Container) getParent() inout { return null; }
void setParent(Container p){}
auto thisAndAllParents(Base : Cell = Cell, bool thisToo = true,
bool isConst=is(typeof(this)==const))() inout{
struct ParentRange{
private Cell act;
private void skip(){
static if(is(Base==Cell)) {}
else while(!empty && (cast(Base)act is null)) popFront;
}
this(const Cell a){ act = cast()a; skip; }
@property bool empty() const{ return act is null; }
void popFront(){ act = act.getParent; skip; }
auto front() {
static if(isConst) return cast(const Base)act;
else return cast( Base)act;
}
}
return ParentRange(thisToo ? this : getParent);
}
auto allParents(Base : Cell = Container)() inout{ return
thisAndAllParents!(Base, false); }
```
More information about the Digitalmars-d-learn
mailing list