C ++ ostream extension

I am trying to learn more about the operation of the C ++ I / O Thread Library by expanding std::streambuf . As a training experiment, my goal is simply to create a custom thread that directs all output to std::cerr . This seems simple enough:

 #include <iostream> using namespace std; class my_ostreambuf : public std::streambuf { public: protected: std::streamsize xsputn(const char * s, std::streamsize n) { std::cerr << "Redirecting to cerr: " << s << std::endl; return n; } }; int main() { my_ostreambuf buf; std::ostream os(&buf); os << "TEST"; } 

This seems to work as it prints Redirecting to cerr: TEST . The problem is that it does not work when a single character (as opposed to a string) is inserted into the stream through std::ostream::sputc . For instance:

 int main() { my_ostreambuf buf; std::ostream os(&buf); os << "ABC"; // works std::string s("TEST"); std::copy(s.begin(), s.end(), std::ostreambuf_iterator<char>(os)); // DOESN'T WORK } 

The problem is, I think xsputn does not handle single character insertion. (I think sputc does not call xsputn internally?) But, by looking at the list of virtual protected functions in std::streambuf , I don't see any function that I have to override that handles the insertion of a single character.

So how can I do this?

+4
source share
1 answer

Single-character output is processed overflow . Here's how you can implement overflow in terms of xsputn if xsputn does the actual output:

 int_type overflow(int_type c = traits_type::eof()) { if (c == traits_type::eof()) return traits_type::eof(); else { char_type ch = traits_type::to_char_type(c); return xsputn(&ch, 1) == 1 ? c : traits_type::eof(); } } 
+4
source

Source: https://habr.com/ru/post/1416461/


All Articles