V2 string

Regan Heath regan at netmail.co.nz
Thu Jul 5 01:51:54 PDT 2007


Walter Bright Wrote:
> Derek Parnell wrote:
> > However, if I might need to update it ...
> > 
> >    char[] fullpath;
> > 
> >    fullpath = CanonicalPath(shortname).dup;
> >    version(Windows)
> >    {
> >       setLowerCase(fullpath);
> >    }
> > 
> > The point is that the 'CanonicalPath' function hasn't got a clue what the
> > calling function is intending to do with the result so it is trying to be
> > responsible by guarding it against mistakes by the caller.
> 
> If you write it like this:
> 
> string fullpath;
> 
> fullpath = CanonicalPath(shortname);
> version(Windows)
> {
>        fullpath = std.string.tolower(fullpath);
> }
> 
> you won't need to do the .dup .

Because tolower does it for you, but it still returns string and if for example you need to add something to the end of the path, like a filename you will end up doing yet another dup somewhere.

I think the solution may be to template all functions which return the input string, or part of the input string, eg.

T tolower(T)(T input)
{
}

That way if you call it with char[] you get a char[] back, if you call it with string you get a string back.

However...

tolower is an interesting case.  As a caller I expect it to modify the string, or perhaps give a modified copy back (both options are valid and should perhaps be supported?).

So, the 'string tolower(string)' version has 2 cases, the first case where it doesn't need to modify the input and can simply return it, no problem.  

But case 2, where it does modify it should dup and return char[].  My reasoning being that after it has completed and returned the copy, the caller now 'owns' the string (as it's the only copy in existance and no-one else has a reference to it).

To achieve that we'd need to overload on return type, or something clever...  but then, how do we call it?

auto s = tolower(input);

tolower cannot be selected at compile time, and the type of s cannot be known either, so that's an impossible situation, yes?

Regan



More information about the Digitalmars-d mailing list