I'm writing a C++ wrapper for a 3rd party C library.
The library provides some functions for iterating through a series of objects.
I want to write an iterator to wrap this behaviour so iteration is easier, but I cannot think how I will be able to provide the mandatory 'difference' type since the iterated objects don't have a meaningful relative order and the API I am working with does not provide a means of finding the number of objects available in advance.
I can't count the objects as they're iterated because although that would solve individual iterators it would render the difference between the end()
iterator and other iterators undefined.
All iterators in C++ need to provide some sort of difference_type
. Whether or not that type is meaningful or useful is a completely separate issue.
From what you're describing, it seems like you're working with an input iterator, which gives you the ability to make a single pass over a stream of data but not to back up or save positions in the stream. For input iterators, there's still a requirement to have a difference_type
defined, but there's no meaningful way to take the difference of two iterators. The only way to measure distance is to manually count up how many elements you've seen as you go.
Using the default of std::ptrdiff_t
is probably very reasonable here unless you have a data stream that can produce so many elements that you can't fit the number of them into a std::ptrdiff_t
. Clients can then use this to count up how many things they've seen, even though your iterator doesn't actually let people compute distances between entries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With