Obtaining const_iterator from iterator

六眼飞鱼酱① 提交于 2019-12-18 04:05:18

问题


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.



来源:https://stackoverflow.com/questions/5105918/obtaining-const-iterator-from-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!