const debacle

Janice Caron caron800 at googlemail.com
Sun Mar 23 01:10:54 PDT 2008


On 22/03/2008, Walter Bright <newshound1 at digitalmars.com> wrote:
> Look at it another way. You want to declare a filter that does not
>  change the input, but can pass it along to another function that will. I
>   suspect this might be a fundamentally broken concept:

I don't think it's a broken concept. In fact, I think that what
Stephen wants is completely reasonable and useful.

Taking what Stephen wants literally, here's how you do it

    const(char)[] f(const(char)[] a)
    {
        /* Stephen's function body */
        return a[1..$];
    }

    char[] f(char[] a)
    {
        return cast(char[]) f(cast(const(char)[])a);
    }

    invariant(char)[] f(invariant(char)[] a)
    {
        return cast(invariant(char)[]) f(cast(const(char)[])a);
    }

While /in general/ it is not safe to cast away constancy, in this
particular case it is obviously safe since all you're doing is
returning a slice of the input.

However, I also argue with Stephen, because I believe that the
following would /also/ work:

    T[] f(T)(T[] a)
    {
        /* Stephen's function body */
        return a[1..$];
    }

or, using the suggestion I made further up the thread

    K(char)[] f(const K)(K(char)[] a)
    {
        /* Stephen's function body */
        return a[1..$];
    }

I know that Stephen will argue with me that the mutable version makes
no promise not to modify the input, but so what? It /doesn't/ modify
the input, and that promise is still there implicitly, because if it
did modify the input then the const version wouldn't compile!

I suppose then that the trick is to prove that the const version
compiles. Well that's easy - just force the const version to
instantiate.



More information about the Digitalmars-d mailing list