Why Strings as Classes?

superdan super at dan.org
Mon Aug 25 19:52:52 PDT 2008


Michel Fortin Wrote:

> On 2008-08-25 21:56:18 -0400, Benji Smith <dlanguage at benjismith.net> said:
> 
> > But if someone else, with special design constraints, needs to 
> > implement a custom container template, it's no problem. As long as the 
> > container provides a function for getting iterators to the container 
> > elements, it can consume any of the STL algorithms too, even if the 
> > performance isn't as good as the performance for a vector.
> 
> Indeed. But notice that the Standard Template Library containers 
> doesn't use inheritance, but templates. You can create your own version 
> of std::string by creating a different class and implementing the same 
> functions, but then every function accepting a std::string would have 
> to be a template capable of accepting either one as input, or changed 
> to use your new string class. That's why std::find and std::foreach, 
> akin many others, are template functions: those would work with your 
> custom string class.
> 
> The situation is no different in D: you can create your own string 
> class or struct, but only functions taking your string class or struct, 
> or template functions where the string type is a template argument, 
> will be able to use it.
> 
> If your argument is that string functions in Phobos should be template 
> functions accepting any kind of string as input, then that sounds 
> reasonable to me. But that's not exacly what you said you wanted.

perfect answer. u da man. 

for example look at this fn from std.string.

int cmp(C1, C2)(in C1[] s1, in C2[] s2); 

so it looks like cmp accepts arrays of any character type. that is cool but the [] limits the thing to builtin arrays. the correct sig is

int cmp(S1, S2)(in S1 s1, in S2 s2) 
    if (isSortaString!(S1) && isSortaString!(S2));

correct?



More information about the Digitalmars-d mailing list