Obtaining const_iterator from iterator

2019-01-24 04:48发布

问题:

Is there a metafunction f that maps an iterator to its corresponding const_iterator?

I.e. f<std::vector<T>::iterator>::type should yield std::vector<T>::const_iterator.

回答1:

I am not aware of such a metafunction.

Not all iterators have a corresponding const_iterator. E.g. insert_iterator. So such a metafunction would need to decide what it is going to do in such cases.



回答2:

I can think of something for a reverse_iterator: using the base member function the decltype, one could extract the return type to get back to the iterator.

However there is no such function for iterator / const_iterator, so it's hard to see how this could be achieved, short of providing an inner typedef or requiring explicit specialization.



回答3:

I think a general solution to your problem (and one that would also be portable is not possible). At least i cannot imagine one :-).

The difficult problem here is that the container defines the const_iterator type. To get to the const_iterator type for the container you have to determine the container type.

However if you start with the iterator type of the container as metafunction parameter it is not possible to retrieve the type of the container.

For known T(s) what you want can be achieved however...



回答4:

I don't think this is possible since there is often no well-defined mapping between iterator types. E.g., two containers could share the non-const iterator type, but have different const iterators. In general you can only map from container types to iterator types, but not between iterator types or from an iterator type to a container type.