Steven Schveighoffer wrote:
"Andrei Alexandrescu" wrote
If Retro.empty is const and Range.empty is not, that won't compile. If
Retro.empty is non-const and Range.empty is const, it will compile, but
passing a const Retro won't work as well as passing a const Range.
Hm... you need the template code to take the place of the designer who looks
at code and decides that something should or should not be const.
For the case of Retro, you'd need some sort of const detection on Range's
empty function.
Exactly. A sort of "auto-qualify". But I guess at that point some people
will throw their hands in the air, and those who'd thrown their hands
already will now throw their feet too. :o)
But in general, when is it necessary for Range.empty to be const (and
therefore Retro.empty to be const)? If Range is working with a const
container, wouldn't you expect that Range itself would not be const, just
the reference to the container is const? A range that doesn't mutate
doesn't seem like a very useful idiom.
I agree, but then I don't want to make many assumptions about future
designs. In general I'm not sure we can always assume the type of the
range and the environment make it easy to obtain mutable ranges for
immutable elements. Probably many people would expect to just write this:
void foo(in SomeRange range) { ... }
and have foo look at the range and its elements no problem, without
actually iterating through the range.
For example, an array range might have empty be const, but a stream range
might not. What matters is what functions you can use those ranges in,
but those are generally templated functions, so the compiler will tell
you whether it can be used or not when it tries to compile it.
Personally, I see no benefit to having empty() be const. What benefits
do you gain by specifically making empty const and the other functions
not const? Presumably, the underlying container must be not const in
order for head, next, etc. to work properly, so there is no requirement
there.
If you have a constant range with random access, empty, length, and
opIndex should be enough for you to look at anything you want without
altering the range itself.
Why not just pass the container itself if the range isn't going to mutate?
The container probably already has opIndex, and length (empty AFAIK plays no
role here). If it doesn't it seems like a bad design to me.
If you have a good example where this is useful, I'd like to hear it.
I need to think that through.
Andrei