const debacle

Janice Caron caron800 at googlemail.com
Sun Mar 23 04:45:50 PDT 2008


Look, let's come up with a real life use case. Let's say we want to
implement a D version of strchr(). How do we declare it? How about

    char[] strchr(char[] s, char c)
    {
        int n = s.find(c);
        return n == -1 ? null : s[n..$];
    }

Trouble is, that declaration suggests that s might be modified. This
means, if there is a bug within the function body which inadvertently
modifies s, the compiler won't catch it.

Fortunately, I think I've already solved the problem, a few posts up.
The solution in this case is:

   T strchr(T : const(char)[])(T s, char c)
   {
        int n = s.find(c);
        return n == -1 ? null : s[n..$];
   }

I don't see that there is anything fundamentally broken about that. T
is any type which will implicitly cast to const(char)[]; you have
compile-time checking that s doesn't get modified within the function;
s /can/ be modified via it's return value /if s is not const/. This is
exactly what's being requested, is it not? Where's the problem with
it?



More information about the Digitalmars-d mailing list