const debacle

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 24 11:54:34 PDT 2008


"Janice Caron" wrote
> On 24/03/2008, Steven Schveighoffer wrote:
>>  > Solution 2: Explicit cast
>>  >
>>  >    T strchr(T)(const T s, char c)
>>  >    {
>>  >        return cast(T)(whatever);
>>  >    }
>>  >
>>  > The declaration of s as "const T" guarantees that the function body
>>  > will not modify s.
>>
>> This does not solve the problem, as if I pass a const T to the function, 
>> it
>>  violates const correctness
>
> Not according to Daniel's code, it doesn't.
>
>       const(char[]) s2b = "0123456789";
>       assert (is(typeof(slice(s2b,1,4)) == typeof(s2b)));

What about:

assert (is(typeof(slice!(char[])(s2b,1,4)) == typeof(s2b)));

It's not a solution if abuse is allowed by the compiler without complaint :)

>>  > Solution 3: Return a range
>>
>> I don't consider this to be a solution because you must implement part of
>>  the function every time you call it.
>
> Trivially solved with macros. (Or at least, it will be, when D has 
> macros).

I hope never to have to use macros, as I hated them in C/C++, and I still 
hate them :)  In any case, having to implement macros to workaround a hole 
in the const system is not going to be a good promoter of using const.

>>  Here is a better case:
>>
>>  T min(T)(T firstval, T secondval)
>>  {
>>   return firstval < secondval ? firstval : secondval;
>>  }
>
> Ooh - now you're changing the ground rules! In your first post, it was
> all about returning a slice into an array. This is a new problem.
>
> It's a good one though! I'm gonna have to think about that for a bit!

Technically, it's the same problem, just a different example :)

-Steve 





More information about the Digitalmars-d mailing list