Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload operator<< (unsigned char typedef as byte)

I want to overload (hijack?) ostream and basic_ostream<unsigned char> so that it stops attempting to display an octet (unsigned char) as a printable character.

I've been living with cout and friends putting smiley faces on the screen for far too long. And I'm tired of working around with casts: hex << int(0xFF & b) << ....

Is it possible to override the standard behavior? I've tried both template and non-template overrides. They compile, but do not appear to be called.

like image 684
jww Avatar asked Aug 15 '11 13:08

jww


1 Answers

The problem is that there already is a

template<class charT, class traits>
std::basic_ostream<charT,traits>& 
operator<<(std::basic_ostream<charT,traits>&, charT);

in namespace std. Since basic_ostream<> is also in this namespace, ADL picks it up when you output an unsigned char. Adding your own overload might make calling the operator ambiguous, or your overload will silently be ignored.

But even if it would work, it would be brittle, because forgetting one include might subtly alter the meaning of the code without any diagnostic from the compiler.
And there's more: Every maintenance programmer looking at such code will assume the standard operator is called (and never think of adding an include when he adds another output statement to the code).
In short, it might be best to add a function doing what you want to do.

A reasonable semantic alternative to that might be to add a stream manipulator that invokes the output format you want. I'm not sure if that's technically possible, though.

like image 63
sbi Avatar answered Nov 11 '22 15:11

sbi