How to fake a const method ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Mar 9 17:37:39 UTC 2018


On Friday, March 09, 2018 14:12:10 Basile B. via Digitalmars-d-learn wrote:
> On Friday, 9 March 2018 at 13:47:34 UTC, Basile B. wrote:
> > I would need this to work:
> >
> > ```
> > struct Foo
> > {
> >
> >     TypeInfo typeCache;
> >
> >     TypeInfo getTypeCache()
> >     {
> >
> >         alias NotThePoint = ubyte;
> >         if (typeCache is null)
> >
> >             typeCache = typeid(NotThePoint);
> >
> >         return typeCache;
> >
> >     }
> >
> >     TypeInfo type() const
> >     {
> >
> >         alias NothrowType = TypeInfo delegate() const;
> >         return (cast(NothrowType) &getTypeCache)();
> >
> >     }
> >
> > }
> >
> > void main(){}
> > ```
> >
> > But get:
> >> Error: mutable method `Foo.getTypeCache` is not callable using
> >> a `const` `this`
> >
> > - `type()` really has to be const because it's used in an
> > opEquals that's used by an AA (key is const so opEquals has to
> > as well)
> > - `typeCache` is not used to compare 2 Foos so it really
> > doesn't matter if it get assigned.
>
> Solved...The error message helped much actually... problem is
> `this` is `const`
>
> https://run.dlang.io/is/UOR2i2

Yes. That's what happens when you mark the function as const. Making the
this pointer/reference const is exactly what marking a member function const
does. However, if your solution involves casting away const, you had better
be 100% sure that the result is never mutated, because if it is mutated,
you're violating the type system and could get weird and subtle bugs. It
would be better if you could just remove const from the equation entirely,
but if you're dealing with AA keys, that's a bit difficult, since they're
immutable (forcing you to deal with either immutable or const).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list