Const template

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Jan 21 07:27:00 PST 2007


Andrei Alexandrescu (See Website for Email) wrote:
> The reflection mechanism would have to provide the information whether
> or not a given member function changes the object.
> 
> The only drawback that I can think right now is that the compiler can't
> exploit this kind of constness with ease to generate better code; it's a
> "user-space" implementation with semantics that are hard to figure out
> at the compiler level.
> 
> A minor drawback is that Const!(Foo) must be implicitly constructible
> from a Foo, but another in-design language feature (opImplicitCast) will
> take care of that.

Correct me if I'm wrong, but I think none of this stuff will work for 
methods that are only declared instead of defined as well; 'const', 
implemented like this, wouldn't work for "header modules"...

For instance:
-----
struct Foo {
     private int data;
     char[] bar();
}
-----
When implemented like you suggest, I don't see any way that Foo.bar() 
can possibly be determined to not change the struct. So will 
Const!(Foo).bar exist?
If not (to be on the safe side) that would seem to limit the use of 
const for something like a closed-source library.
If it *does* exist, that would easily (and perhaps accidentally) 
circumvent the meaning of const.


I also don't see a way this can work for classes (in general). There's 
no way to limit a non-final method to non-mutating operations that I'm 
aware of, so it could easily be circumvented by subclassing. Even though 
that would only allow direct access to non-private fields, mutating base 
class methods could still be called for the rest (if available). So then 
the only way to get a const version of a class would be if the class 
doesn't allow mutations anyway (like java's String). Which leaves us 
right back where we started :(.

And I don't think a 'const' implementation should work for structs and 
not for classes...



More information about the Digitalmars-d mailing list