`this` template params for struct not expressing constness.
Simen Kjærås
simen.kjaras at gmail.com
Mon Jun 8 10:30:33 UTC 2020
On Monday, 8 June 2020 at 09:08:40 UTC, adnan338 wrote:
> On Monday, 8 June 2020 at 08:10:19 UTC, Simen Kjærås wrote:
>> On Monday, 8 June 2020 at 07:35:12 UTC, adnan338 wrote:
>>> Self* searchTree(this Self)(auto in ref T item) const {
>>> if (&this is null)
>>> return null;
>>> if (this.item == item)
>>> return &this;
>>> return (this.item < item) ?
>>> this.right.searchTree(item) :
>>> this.right.searchTree(item);
>>> }
>>
>> This method is const, which means 'this' is const, while Self
>> is not. What you're looking for here is inout
>> (https://dlang.org/spec/function.html#inout-functions):
>>
>> auto searchTree()(auto in ref T item) inout {
>> if (&this is null)
>> return null;
>> if (this.item == item)
>> return &this;
>> return (this.item < item) ?
>> this.right.searchTree(item) :
>> this.right.searchTree(item);
>> }
>>
>> --
>> Simen
>
> Thank you. Few followup questions, if you don't mind.
>
> 1. What does that blank template parameter mean?
Just forces the function to be a template. The only reason for
this is it's required for auto ref to work, which you may or may
not need on that function.
> 2. Since `inout` acts as a wildcard for
> immutable/const/non-const qualifiers, what should I do to have
> the compiler ensure that my method does not mutate a non-const
> tree inside the body?
Inside inout functions, `this` is treated as const - any attempt
to modify it should give a compile error. Since D const is
transitive, anything reachable from `this` is also treated as
const. If you're able to mutate a non-const tree inside the
body, there's a bug in the compiler.
--
Simen
More information about the Digitalmars-d-learn
mailing list