Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing istringstream with string_view doesn't compile

Tags:

c++

c++17

I'm not able to provide a std::string_view to std::istringstream's constructor. The following code doesn't compile (C++17 enabled using Clang v8):

std::string_view val = "Hello";
std::istringstream ss(val, std::ios_base::in);

The error I get is:

prog.cc:9:24: error: no matching constructor for initialization of 'std::istringstream' (aka 'basic_istringstream<char>')
    std::istringstream ss(val, std::ios_base::in);
                       ^  ~~~~~~~~~~~~~~~~~~~~~~
/opt/wandbox/clang-6.0.0/include/c++/v1/sstream:651:14: note: candidate constructor not viable: no known conversion from 'std::string_view' (aka 'basic_string_view<char>') to 'const std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char> >::string_type' (aka 'const basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >') for 1st argument
    explicit basic_istringstream(const string_type& __s,
             ^

However this does:

std::string_view val = "Hello";
std::istringstream ss(val.data(), std::ios_base::in);

This issue is weird to me because there's only 1 implicit conversion that should be happening here: std::string_view to std::basic_string. The constructor is taking a basic_string according to the error message.

Why can't I use string_view verbatim here without calling string_view::data()?

like image 840
void.pointer Avatar asked Mar 04 '23 16:03

void.pointer


1 Answers

This issue is weird to me because there's only 1 implicit conversion that should be happening here: std::string_view to std::basic_string.

A string_view is not implicitly convertible to a string. The constructor (ok, deduction guide, but whatever) is marked as explicit.

This should work (untested):

std::string_view val = "Hello";
std::istringstream ss(std::string(val), std::ios_base::in);

The reason for the explicit is that it's a (potentially) expensive operation; involving memory allocation and copying of the data. The opposite conversion (string --> string_view) is cheap, and as such is implicit.

like image 70
Marshall Clow Avatar answered Mar 06 '23 05:03

Marshall Clow