My question is really simple: Is there a type in the standard whose purpose is to store the begin-terator and the end-iterator for a container?
I want to return both iterators from a single function. I'm aware I could use std::pair for this but it feels like there would be some type in the standard for this exact purpose. I've scanned the <iterator> header but can't seem to find a type like this. I'm not that good at iterator terminology so I'm not sure if one of those actually do what I'm looking for. Is there one that does?
(If you're interested in why I even want to do it in the first place, I have constant arrays in a class template that derives from a base class. Using polymorphism I want to iterate over their class constants, but I obviously can't have the virtual functions of the base class return the actual arrays since those are templated. Hence, I have virtual functions returning plain pointers, called someArrayBegin(), someArrayEnd(), otherArrayBegin(), etc, that I override in the derived class template to return the correct addresses.)
CodePudding user response:
Is there a type in the standard for storing the begin- and end-iterators of a container?
Your description matches closely with the concept of a range.
std::ranges::subrange can be created from a pair of iterators. That will be templated based on the iterator type.
If you need to hide the iterator type for runtime polymorphism, you would need ranges::any_view which unfortunately isn't in the standard implementation of the ranges. Furthermore, there is a runtime cost associated with it.
For contiguous containers, another alternative is std::span which can point to any contiguous range without the cost of type erasure. For strings in particular, yet another alternative is std::string_view.
