Const template
Sean Kelly
sean at f4.ca
Tue Jan 23 00:09:38 PST 2007
Lionello Lunesu wrote:
> Bruno Medeiros wrote:
>> Andrei Alexandrescu (See Website For Email) wrote:
>>> Frits van Bommel wrote:
>>>> You didn't respond to my paragraph on classes though:
>>>>
>>>> Frits van Bommel wrote:
>>>> > 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...
>>>
>>> I did when I wrote:
>>>
>>> >> That is correct. Interface functions, nonfinal methods, and
>>> >> declared-only functions must be annotated manually.
>>>
>>> I meant - yes, you are right.
>>>
>>> Today, Walter and myself have come with a semantics for const (as in,
>>> "read-only view" that) seems to be a good starting point. The details
>>> are yet to be ironed out, but here's the basic plot:
>>>
>>
>> So the keyword for the "read-only view" will be 'const' too? It will
>> share space with the 'const' as in "compile time constant" ?
>
> 'const' is not always a compile time constant. A const in function or in
> a class can have a different value for each call/instance. Don't ask me
> why.
I ran into this problem recently:
module a;
class C
{
const int val;
static this() { val = 1; }
}
C:\code\src\d\test>dmd test
test.d(7): Error: can only initialize const val inside constructor
I'm sure this is a bug but haven't reported it yet. Trying to use a
static module ctor to init the class const doesn't work either. But if
the const is global then all is well.
Sean
More information about the Digitalmars-d
mailing list