• Advertisement

Archived

This topic is now archived and is closed to further replies.

Manipulator error

This topic is 4973 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can someone tell me why the following line of code won''t compile?
std::ofstream& CLogFile::endl (std::ofstream &out)
{
	return out << "
"; }
The error states:
''return'' : cannot convert from ''class std::basic_ostream >'' t
o ''class std::basic_ofstream > &''
        A reference that is not to ''const'' cannot be bound to a non-lvalue
 
It seems to be complaining that I''m trying to convert an ostream to an ofstream, but as far as I can see I''m not.

Share this post


Link to post
Share on other sites
Advertisement
Try breaking the return into two lines:

std::ofstream& CLogFile::endl (std::ofstream &out) {
out << " ";
return out;
}

Share this post


Link to post
Share on other sites
To expand on that (assuming I do actually understand what''s going on):

ofstream is-a ostream. The operator<< on ofstream returns *this, but returns it as a more general ostream&, in accordance with some people''s ideas about good OO practice (don''t tell people more than they need to know about the returned object). So breaking the statement into two lines will do the trick (you throw the returned *this value on the floor, and do the return yourself, as an ofstream); casting should as well (but is probably a Bad Idea(TM)); as should just returning an ostream& yourself (why not follow the library designers'' lead?).

Share this post


Link to post
Share on other sites
quote:
Original post by Zahlman
but returns it as a more general ostream&, in accordance with some people''s ideas about good OO practice (don''t tell people more than they need to know about the returned object).


Not all overloads of operator<< on std::basic_ostream are defined to return *this. For example, std::basic_ostream & std::basic_ostream<<(std:basic_ostream & (*pf)(std::basic_ostream &)) is defined to return pf(*this), which may not even be the original stream. Therefore, it is impossible to define operator<< to have covariant returns for all overloads. It doesn''t really have anything to do with minimizing type information on return types, but more to do with orthogonality in interface.

Share this post


Link to post
Share on other sites

  • Advertisement