range and algorithm-related stuff

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 27 09:09:49 PST 2009


"Denis Koroskin" wrote
> On Tue, 27 Jan 2009 05:13:31 +0300, Steven Schveighoffer 
> <schveiguy at yahoo.com> wrote:
>
>> "Denis Koroskin" wrote
>>> On Mon, 26 Jan 2009 23:37:25 +0300, Denis Koroskin <2korden at gmail.com>
>>> wrote:
>>>> Checking if a range is empty() prior to accessing its head is useful. 
>>>> If
>>>> empty() is const, you can't do that.
>>>
>>> Err.. if empty() is not const and you have a const range reference.
>>
>> empty not being const does not imply that you can't access a const 
>> member.
>> Empty not being const allows all access.  The question is whether a 
>> wrapping
>> range (or any range for that matter) should implement empty as const, as 
>> an
>> empty that IS const cannot call a non-const function of a member.
>>
>> -Steve
>>
>>
>
> I didn't say non-const empty restricts any member access, did I?

Sorry, I sort of misinterpreted what you said.  You said, "If empty() is 
const you can't do that." and then sent out a followup email saying "Err.. 
if empty() is not const and you have a const range reference."  I 
interpreted that as you replacing the statement "If empty() is const" with 
"if empty() is not const and you have a const range reference," making the 
complete statement "if empty() is not const and you have a const range 
reference, you can't do that."  Which means I thought you meant, if you have 
an empty that is not const and a const range reference (which I interpreted 
as the reference to the data inside the range), then empty cannot access the 
const member.  I see now what you were saying.

However, I don't think this is a common situation.  A range is a struct so 
it can be a value type.  Having a const reference to a range means you can 
easily copy everything out of the const range to a non-const range with a 
const reference to the data.  Note that if I parameterize my range based on 
the data type, const Range!(T) should be implicitly convertable to 
Range!(const T), where the range itself is made mutable, but the data 
reference is const.  So there is little point to making a range itself 
const.

That being said, I'll also point out that creating a const range reference 
to access a single element from a range is a very questionable practice, the 
design might be better served to just access that element directly from the 
data container itself.  Similarly with random access, any container that 
provides a random access range to its data will most likely also provide an 
opIndex to get the data directly.  Ranges being structs, they are only 
really useful in functions that already know the data type, or template 
functions which are told the data type.  I don't see any reason why you 
can't substitute the data structure itself that supplies a length and 
opIndex member instead of the range.

-Steve 





More information about the Digitalmars-d mailing list