tags:

views:

120

answers:

3

Just for clarification, I'm referring to the global getline() function in the string class.

What I want to do is to have something like this:

int main()
{
   wifstream in(L"textfile.txt");
   someFunc(in);
   return 0;
}


void someFunc(const wistream& read)
{
   wstring buff;

   while(getline(read, buff))
   {
      //do some processing here
   }
}

but I'm getting a:

Error   2 error C2664: 'std::getline' : cannot convert parameter 1 from 'const std::wistream' to 'std::basic_istream<_Elem,_Traits> &'

In order to fix it, I need to remove the const from const wistream& read. I understand why this is happening but is it possible to configure getline() to accept a wistream instead without any conversions or should I just ignore it and remove the const?

+4  A: 

It does accept a wistream, but getline() demands a non-const argument because it modifies the stream. Try changing it to:

...
void someFunc(wistream& read)
...
luke
Yes, I understand that and I already noted that in the question
scratch that, brain fart!!
I misread your question, which is a little confusing. You know how to solve the problem, but you seem to misunderstand why it is happening... I think :) I have amended my response.
luke
+3  A: 

Reading characters from the stream modifies the stream. You can't mark the stream const and expect that to work correctly.

John Ledbetter
A: 

As a rule of thumb,

  1. I always pass function parameters as const references
  2. unless they are built-in types, in which case they are copied (and const/non-const becomes a question of style)
  3. unless they are meant to be changed inside the function so that the changes reflect at the caller's, then they are passed by non-const reference
  4. unless the function should be callable even if callers don't have an object to pass, then they are passed as pointers (#1 and #3 applies here, too)

Streams, however, are a notable exception from that rule, as they must always be passed around as non-const references.

sbi
Not really an exception - streams do get changed when read from. So it is covered by your case 3.
Nemanja Trifunovic
From teaching I learned that most novices see this as an exception, since they don't feel like they are changing the stream when they are using it. (I'm open to both sides.)
sbi