Container hierarchy vs. container types
Jonathan M Davis
jmdavisProg at gmail.com
Fri Mar 5 12:20:32 PST 2010
Michel Fortin wrote:
> On 2010-03-05 11:32:27 -0500, Jonathan M Davis <jmdavisProg at gmail.com>
> said:
>
>>> Why couldn't a container have the same interface as a range, only with
>>> the added ability to push elements into it?
>>
>> Probably because it would become way too easy to accidentally use the
>> container as a range, which in many cases would end up emptying it when
>> passing it to one of the std algorithms.
>
> Yes, I understand that.
>
> My point is that the problem already exists with ranges: by exposing a
> stream as a range, you'll empty the stream when iterating over it. If
> that's acceptable for streams, why is it not for containers?
>
> And perhaps you actually want to empty the container as you iterate
> over it. If you use your container as a queue, that's what you'll
> expect. In fact, a stream is just like a queue, and you want algorithms
> to work on streams don't you?
>
It would probably be better in such a case to have a range wrap the
container. That way, you can have range semantics for the container if you
want them, but you don't risk using them on a container where you don't.
As for streams, I don't know. I do like the idea of using ranges with
streams, but I haven't really looked at what the downsides to that might be.
It depends a lot on what the std algorithms do. With some it might be fine
while with others it would be a really bad idea. I'd have to look into it
more to say, but at least with a stream, it's expected that iterating over
it will alter it. With a container, that's not usually the case. And in
cases where it is, either that container could be a special case and be a
range as well, or it you could have a wrapper range do it. Personally, I'd
prefer the wrapper idea. It would probably allow you to create generic
wrappers to use on pretty much any container (or at least containers with a
particular set of functions) rather than special casing particular
containers. Regardless, I think that making containers ranges in the general
case is a bad idea.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list