Search code examples
c++c++17stdstringstring-view

Why can't I create a std::string_view from std::string iterators?


It is possible to create a std::string_view from a std::string easily. But if I want to create a string view of a range of std::string using the iterators of the std::string does not work.

Here is the code that I tried: https://gcc.godbolt.org/z/xrodd8PMq

#include <iostream>
#include <string>
#include <string_view>
#include <iterator>

int main()
{
    std::string str{"My String"};
    std::string_view strView{str};  // works
    //std::string_view strSubView{str.begin(), str.begin() + 2}; // error
}

Of course maybe we can make the substring out from str and use to make a string view strSubView, but there is an extra string creation.

I found that the std::basic_string_view s fifth constructor takes the range of iterators.

template<class It, class End>
constexpr basic_string_view(It first, End last);

But is it only the iterators of the std::string or just std::basic_string_view 's itself? If not for std::string's iterates why shouldn't be we have one, after all the string view:

describes an object that can refer to a constant contiguous sequence of char-like objects !

Taking the range of contiguous sequence of char, should not we count?


Solution

  • That constructor is added in C++20. If you are compiling with a C++17 compiler then it isn't present.

    You can write a function that does the same thing

    std::string_view range_to_view(std::string::iterator first, std::string::iterator last) {
        return first != last ? { first.operator->(), last - first } : { nullptr, 0 };
    }