From what I understand, the purpose of size_type and difference_type is not merely the sign — it was also meant to address e.g. segmented architectures and such, where they might be of different sizes.
With that context, if I have a container with random-access iterators, is it safe for me to perform a static_cast between its difference_type and size_type values at will, on the grounds that end() - begin() must always be equal to size(), when either is casted?
(The use case, for example, is to create a container whose size is equal to the number of elements between two iterators, or the reverse: to copy a container of a certain size onto a range delimited by iterators.)
Anything I should watch out for before casting (e.g. loss of data)?
Here’s what the C++11 standard has to say on various things here:
§ 23.2.1
Let’s make sure
size()is equivalent toend() - begin():§ 24.4.4/4
Since your container has random-access iterators, this holds true. That’s that. As you can see in the first box,
From that, we have that the cast from
difference_typetosize_typeshould be valid for all non-negative values.