Why Strings as Classes?

Michel Fortin michel.fortin at michelf.com
Mon Aug 25 19:43:27 PDT 2008


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.

> There's no good reason the same technique couldn't provide both speed 
> and API flexibility for text processing.

This is absolutely right... but unfortunately, using virtual 
inheritance (as interfaces in D imply) isn't the same technique as in 
the STL at all. Template algorithms parametrized on the container and 
iterator type is what the STL is all about, and from there come its 
speed.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list