The Status of Const

Pelle pelle.mansson at gmail.com
Tue Aug 17 10:01:11 PDT 2010


On 08/17/2010 02:48 PM, Steven Schveighoffer wrote:
> On Tue, 17 Aug 2010 06:05:55 -0400, Pelle <pelle.mansson at gmail.com> wrote:
>
>> On 08/17/2010 01:44 AM, Steven Schveighoffer wrote:
>>> On Mon, 16 Aug 2010 19:06:56 -0400, Simen kjaeraas
>>> <simen.kjaras at gmail.com> wrote:
>>>> Uhm, it works in D:
>>>>
>>>> class C {}
>>>> class D : C {}
>>>>
>>>> void main( ) {
>>>> D[] a;
>>>> C[] b = a;
>>>> }
>>>
>>> Yes, I was about to say that except that is a bug kind of. The type
>>> system should only allow casting D[] to const(C)[].
>>
>> class C { }
>> class D : C { }
>> class E : C { }
>>
>> void append_to(ref const(C)[] cs, const(C) c) { cs ~= c; }
>>
>> D[] ds;
>> append_to(ds, new E);
>>
>>
>> *ahem*
>> D[] can not be converted to const(C). That it works today is pretty
>> terrible. Rewrite the append_to to work with Objects, and well. :-)
>
> It's a bug also :)
>
> The general rule of thumb is that you can convert a reference to a type
> to a reference to a const subtype that's only a one-level reference.
> *two* level references cannot be converted, because of the example you
> showed. A ref const(C)[] is a two-level reference (reference to array,
> which is a reference to a block of const(C)). So you cannot convert a
> ref const(D)[] into a ref const(C)[], but converting a const(D)[] into a
> const(C)[] is ok because there is only one level of reference before you
> reach the const type.
>
> -Steve

I just saw that I missed the ref part when I tried the code, and my 
example does not actually compile. Phew!


More information about the Digitalmars-d mailing list