const and non-const member function
Christian Kamm
kamm.incasoftware at shift-at-left-and-remove-this.de
Thu Jul 26 00:04:40 PDT 2007
> I may be wrong, but I think the idea is that a method either is or isn't
> const-safe, and the difference between const and mutable references to
> the object is supposed to be in the availability of methods, not in
> their behavior. While I'm sure there's some percentage of the time
> subtle behavioral changes could be desirable, I don't believe
> const-method overloading is meant to happen.
>
> That said, a few demonstrative cases sometimes do wonders. :)
Well, the original poster basically wanted it to be possible to have
class Container(T)
{
int opApply(int delegate(ref T) dg);
const int opApply(int delegate(ref const(T)) dg);
}
such that foreach would work on const(Container!(T)) and Container!(T)
alike, using the correct types. To me, that seems pretty reasonable.
James Dennett pointed out another, simpler example
Foo getThis() { return this; }
const const(Foo) getThis() { return this; }
invariant invariant(Foo) getThis() { return this; }
Personally, I'd like to see the 'templating on const' solution that was
thrown around during one of the const debates
C C(Foo) getThis(constness C)() { return this; }
and
C int opApply(constness C)(int delegate(ref C(T)) dg)
as the different versions are usually quite similar, except for slightly
different types.
> (I'm also not 100% pleased with the 'const R M(){}' syntax for declaring
> const methods...
Yes, it's quite bad:
const Foo func(const Foo)
{
const Foo = ...;
}
All consts look the same, but the first means the method, the second is an
alternative for const(Foo) and the third is the compile-time const storage
class.
I'd probably disallow const Foo in parameter declarations, yet don't know
how to do make the method-const look different.
Cheers,
Christian
More information about the Digitalmars-d-learn
mailing list