Why aren't ranges' algorithms compatible with std's iterators?

后端 未结 1 1038
说谎
说谎 2020-12-09 18:16
#include 
#include 
#include 

int main()
{
    auto coll = std::vector{ 1, 2, 3 };

    ranges::copy(
                 


        
相关标签:
1条回答
  • 2020-12-09 19:22

    To me, the generic algorithm copy shouldn't care about the destination iterator type as long as it meets the requirements of output iterator.

    This is correct. It's not that ranges::copy somehow recognizes ranges::ostream_iterator and not std::ostream_iterator. It's that Ranges has a refined concept for what an OutputIterator is, such that ranges::ostream_iterator does model OutputIterator but std::ostream_iterator does not.

    Specifically, ranges::copy() requires WeaklyIncrementable<O> which refines SemiRegular<O> which requires DefaultConstructible. ranges::ostream_iterator is default constructible, but std::ostream_iterator is not.

    Hence the failure.


    In P0896, the range-based copy() algorithm does require WeaklyIncrementable (and thus DefaultConstructible) for its output iterator - but addresses this mismatch by also adding a default constructor to std::ostream_iterator (see page 70).


    Note that the range-v3/Ranges TS/Ranges Proposal concept OutputIterator is separate from the standard library's existing concept of OutputIterator. std::ostream_iterator does not model the former but it does model the latter - so using std::copy with a std::ostream_iterator today is perfectly fine. And post-P0896, using ranges::copy with a std::ostream_iterator will also be fine - because of the proposed changes to std::ostream_iterator.

    0 讨论(0)
提交回复
热议问题