const debacle

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 21 11:15:10 PDT 2008


"Sean Kelly" wrote in message
> == Quote from Steven Schveighoffer
>> This issue was just brought to my attention, and I wonder if the other
>> const-proponents have a good solution for this.  This is going to be very
>> tough to deal with.
>> How do you declare a function that takes an array, is not allowed to 
>> change
>> the array, but returns a slice into the argument array, and the return 
>> type
>> matches the argument type.
>> For example, if I pass a mutable array to this function, I want it to 
>> pass
>> me back a mutable slice into the array, but I also want a guarantee that 
>> the
>> function will not modify the array.  I can't declare the argument is 
>> const
>> because then the return value must also be const, as it is a slice of the
>> original array.
>> How does one solve this problem?
>
> Use overloaded functions.  In theory, I think this should work:
>
> T[] func(T)( T[] buf ) { ... }
> const T[] func(T)( const T[] buf ) { ... }
> invariant T[] func(T)( invariant T[] buf ) { ... }
>
> Even if D doesn't overload on const-ness (I seem to recall that it doesn't 
> right now), I think the above
> set of functions won't conflict because one will be more specialized than 
> the other, based on the
> supplied type.  However, this aspect of D is fairly primitive so it's 
> somewhat of a shot in the dark.
> Weren't templates in 2.0 eventually supposed to get some way to learn the 
> const-ness of a parameter?  I
> seem to recall that from Walter and Andrei's conference presentation.
>
>
> Sean

Hm... can't you just do this like:

T[] func(T)(T[] buf) {...}

and T will be either const(T), invariant(T), or just T?

In any case, the crux of the problem is still there.  For the version with 
just T, the compiler is not guaranteeing that func doesn't modify the input.

-Steve 





More information about the Digitalmars-d mailing list