Skip to main content
gamedev.net
🔒 Locked

Manipulator error

Started by Anima 2 replies 250+ views
Original Post
Anima
Anima
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.
SiCrane
SiCrane
Try breaking the return into two lines:

std::ofstream& CLogFile::endl (std::ofstream &out) {
out << " ";
return out;
}
Zahlman
Zahlman
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?).
SiCrane
SiCrane
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.