Why can't GCC and Clang compile the code snippet below (link)? I want to return a vector of std::string_views but apparently there is no way of extracting string_views from the stringstream.
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <iterator>
#include <algorithm>
#include <ranges>
[[ nodiscard ]] std::vector< std::string_view >
tokenize( const std::string_view inputStr, const size_t expectedTokenCount )
{
std::vector< std::string_view > foundTokens { };
if ( inputStr.empty( ) ) [[ unlikely ]]
{
return foundTokens;
}
std::stringstream ss;
ss << inputStr;
foundTokens.reserve( expectedTokenCount );
std::copy( std::istream_iterator< std::string_view >{ ss }, // does not compile
std::istream_iterator< std::string_view >{ },
std::back_inserter( foundTokens ) );
return foundTokens;
}
int main( )
{
using std::string_view_literals::operator""sv;
constexpr auto text { "Today is a nice day."sv };
const auto tokens { tokenize( text, 4 ) };
std::cout << tokens.size( ) << '\n';
std::ranges::copy( tokens, std::ostream_iterator< std::string_view >{ std::cout, "\n" } );
}
Note that replacing select instances of string_view with string lets the code compile.
string_view?string_viewobject being passed totokenizeis managed by the call site (in this case, it's themainfunction).string_views you store in your vector.string_viewas its template argument?std::string_viewis fancy form of const reference, so problem is same as stream iterator to const reference.