Generic const - a non-functional view

Steven Schveighoffer schveiguy at yahoo.com
Wed Jun 25 11:07:28 PDT 2008


"Jason House" wrote
> Steven Schveighoffer Wrote:
>
>> "Jason House" wrote
>> >  Consider this template:
>> >
>> > class array(T){
>> >  typedef element T elem;
>> >  elem contents[];
>> > }
>> >
>> > Maybe I got the syntax wrong, but the basic idea is that T and element 
>> > are
>> > really the same kind of thing.  array!(const T) and
>> > const!(element)(array!(T)) are different types.  Should they be?  I 
>> > don't
>> > think so.  There's still something buried in a tail const scheme that
>> > still needs to get fleshed out, somehow...
>>
>> Tail const is much more possible with the const scheme I outlined.  Your
>> example is not really relevant because the entire set of members is 
>> marked
>> by a tag.  This is no different than today's const.
>
> Actually, it is different.  The array is resizable, so not everything 
> inside is constant.  I'm sure using an array inside a class is far less 
> clear for const examples, but I was trying to show the parallels with a 
> simple array.

Yes, I stand corrected.  For your example const(array!(T)) is different than 
array!(const T).  My mistake.

>> Basically, as a simple rough explanation, what I propose allows you to
>> direct const to apply only to certain pieces of a struct or class, 
>> instead
>> of always affecting the whole thing.  Tail const is possible because you 
>> can
>> tag only the 'pointed to' data and const-ify only that part.
>>
>> Another aspect is this:
>>
>> array!(T) and array!(const T) are not implicitly castable, because they 
>> are
>> two separate types.  e.g.:
>>
>> array!(T) t = new array!(T)(5); // array of 5 Ts
>>
>> const(array!(T)) t2 = t; // ok, t2 is the same type, but with a const
>> modifier.
>>
>> array!(const T) t3 = t; // error, incompatible types
>>
>> const!(element)(array!(T)) t4 = t; // ok, because t4 is the same type, 
>> but
>> with a const modifier.
>
> That's all true as proposed.  The deeper question is should it be that 
> way?  When should having a const argument as a template parameter result 
> in a whole new type and when should implicit casts to const template 
> parameters be allowed?

The problem is that with template compile-time evaluation, one can construct 
a completely different template for const T than for T.  With the generic 
const proposal, you cannot do this, as there is no generated type based on 
whether something is const or not.  The compiler would have to disallow this 
kind of thing, or else have a special way to identify the constancy as not 
varying the template generated.  But I much prefer not dealing with 
templates at all.

If there is a simpler way to do it, then I'm all for that.

-Steve 





More information about the Digitalmars-d mailing list