Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, function that can take either ifstream or istringstream

I have a function do_something that reads unsigned characters from a stream.

The stream can be created from a file given the file name. Or it can be created from the given string by considering it as data. I would like to reuse the function in both cases.

The code below gives an error in the second case: "error C2664: 'do_something: cannot convert argument 1 from 'std::basic_istringstream' to 'std::basic_istream'".

What is the proper way to do this?

static void do_something(std::basic_istream<unsigned char>& in)
{
   in.get();
}

static void string_read(unsigned char* in)
{
   std::basic_ifstream<unsigned char> file(std::string("filename"));
   do_something(file);

   std::basic_istringstream<unsigned char> str(std::basic_string<unsigned char>(in));
   do_something(str);
}
like image 731
klk206 Avatar asked Jul 17 '20 18:07

klk206


People also ask

How do I convert ifstream to Istringstream?

You cannot convert a std::ifstream directly to a std::istringstream . However, your function that uses a std::istringstream should simply be rewritten to use a std::istream instead, so that it can be used both with std::istringstream and std::ifstream .

What is std :: Istringstream?

The std::istringstream is a string class object which is used to stream the string into different variables and similarly files can be stream into strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed as a string object.

Is ifstream a data type?

An object of type ifstream is an "input file stream" that can be used to read data from a file into variables.


1 Answers

Your code is experiencing something called a vexing parse. The line:

std::basic_istringstream<unsigned char> str(std::basic_string<unsigned char>(in));

is interpreted as a function declaration. str here is a function that returns a std::istringstream and takes as its parameter a variable of type std::string called in. So when you pass it into the function there's an obvious type mismatch.

To change it into a variable declaration you can use curly braces:

std::basic_istringstream<unsigned char> str{std::basic_string<unsigned char>(in)};
like image 199
David G Avatar answered Sep 20 '22 15:09

David G