const debacle
Steven Schveighoffer
schveiguy at yahoo.com
Mon Mar 24 10:59:59 PDT 2008
"Janice Caron" wrote
> On 24/03/2008, Steven Schveighoffer wrote:
>> No, it is not a solved problem. As a caller of a function, you still
>> cannot
>> rely on the compiler verifying that a function does not modify it's
>> arguments for mutable arguments.
>
> I don't follow that. I believe that at least two of the three
> solutions do indeed make that guarantee.
>
> 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, just like the C version did.
> Solution 3: Return a range
>
> Range!(uint) strchr(const(char)[] s, char c)
>
> The declaration of s as "const(char)[]" guarantees that the function
> body will not modify the elements of s.
I don't consider this to be a solution because you must implement part of
the function every time you call it. Here is a better case:
T min(T)(T firstval, T secondval)
{
return firstval < secondval ? firstval : secondval;
}
This should have const on firstval and secondval, even if T is a mutable
type, but because of the current const rules, it can't. As a user of min, I
am still forced to read the implementation of the function, or trust the
implementor of the function to have done what he says it does (and for
him/her to have checked all the functions he might call). I'd much rather
trust the compiler, and not worry about it.
Yes, you could rewrite the function as:
bool less(T)(const(T) firstval, const(T) secondval)
{
return firstval < secondval;
}
// x = min(x, y);
x = less(x, y) ? x : y;
Now this function is totally useless as I can rewrite it as:
x = x < y ? x : y;
I don't like this general design idea because the caller must know how to
build the 'real' result based on the parameters given back, and basically
must re-implement some or all of the function every time he/she calls it.
There are more abstract cases too, that you would almost have to return a
delegate, and have the user call the delegate on the parameter again! Think
of how awful implementing such a function would be. I'd much rather have
the function itself construct the result in the way it wants to, then tell
the caller how to construct it.
-Steve
More information about the Digitalmars-d
mailing list