1

C++20 adds a constructor for basic_string_view which takes two iterators. However, when I try to construct a string_view with the iterators from a common range I get an error.

#include <iostream>
#include <ranges>

using namespace std::views;

int main()
{
    auto words = "the quick brown fox" | split(' ') | transform([]<class RNG>(RNG&& rng) {
        auto v = std::views::common(std::forward<RNG>(rng));
        return std::string_view(v.begin(), v.end());
    });
    for (auto&& word : words) {
        std::cout << word << std::endl;
    }
}

<source>:11:6:   required from here
<source>:10:21: error: no matching function for call to 'std::basic_string_view<char>::basic_string_view(std::common_iterator<std::ranges::split_view<std::ranges::ref_view<const char [20]>, std::ranges::single_view<char> >::_InnerIter<true>, std::default_sentinel_t>, std::common_iterator<std::ranges::split_view<std::ranges::ref_view<const char [20]>, std::ranges::single_view<char> >::_InnerIter<true>, std::default_sentinel_t>)'
10 |         return std::string_view(v.begin(), v.end());
    |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

https://godbolt.org/z/E4779G

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Chris_F
  • 4,991
  • 5
  • 33
  • 63
  • Does this answer your question? [How to split a std::string into a range (v3) of std::string\_views?](https://stackoverflow.com/questions/48402558/how-to-split-a-stdstring-into-a-range-v3-of-stdstring-views) – 康桓瑋 Mar 18 '21 at 13:32
  • @康桓瑋 actually the question you linked is only tangentially relevant here – bartop Mar 18 '21 at 13:36
  • @bartop By tangentially, you mean it's exactly the same question but just about range-v3 instead of C++20? – Barry Mar 18 '21 at 13:56
  • @Barry no, I mean that though code is similar, the questions are rather different – bartop Mar 18 '21 at 13:57
  • You can't really split a string literal: the trailing null after "fox" will be included in the last word. Make sure you cast to a `string_view` first. – Barry Mar 18 '21 at 13:57

1 Answers1

2

Notice the requirements imposed on the iterator constructor for std::string_view:

This overload only participates in overload resolution if

  • It satisfies contiguous_iterator,
  • End satisfies sized_sentinel_for for It,
  • std::iter_value_t and CharT are the same type, and
  • End is not convertible to std::size_t.

Your range iterators do not satisfy at least the first requirement

bartop
  • 9,971
  • 1
  • 23
  • 54