मुझे नहीं पता कि यह सही समाधान है, लेकिन मुझे इस तरह std :: ostream से विरासत मिली है। यह std :: basic_streambuf से विरासत में प्राप्त एक बफर का उपयोग करता है और एक समय में 64 वर्ण प्राप्त करता है (या फ़्लश होने पर कम) और उन्हें सामान्य जेन चार्स() विधि में भेजता है जहां डेटा का वास्तविक प्रबंधन किया जाता है। यह भी दर्शाता है कि उपयोगकर्ता डेटा कैसे देना है।
Live Example
#include <streambuf>
#include <ostream>
#include <iostream>
//#define DEBUG
class MyData
{
//example data class, not used
};
class MyBuffer : public std::basic_streambuf<char, std::char_traits<char> >
{
public:
inline MyBuffer(MyData data) :
data(data)
{
setp(buf, buf + BUF_SIZE);
}
protected:
// This is called when buffer becomes full. If
// buffer is not used, then this is called every
// time when characters are put to stream.
inline virtual int overflow(int c = Traits::eof())
{
#ifdef DEBUG
std::cout << "(over)";
#endif
// Handle output
putChars(pbase(), pptr());
if (c != Traits::eof()) {
char c2 = c;
// Handle the one character that didn't fit to buffer
putChars(&c2, &c2 + 1);
}
// This tells that buffer is empty again
setp(buf, buf + BUF_SIZE);
return c;
}
// This function is called when stream is flushed,
// for example when std::endl is put to stream.
inline virtual int sync(void)
{
// Handle output
putChars(pbase(), pptr());
// This tells that buffer is empty again
setp(buf, buf + BUF_SIZE);
return 0;
}
private:
// For EOF detection
typedef std::char_traits<char> Traits;
// Work in buffer mode. It is also possible to work without buffer.
static const size_t BUF_SIZE = 64;
char buf[BUF_SIZE];
// This is the example userdata
MyData data;
// In this function, the characters are parsed.
inline void putChars(const char* begin, const char* end){
#ifdef DEBUG
std::cout << "(putChars(" << static_cast<const void*>(begin) <<
"," << static_cast<const void*>(end) << "))";
#endif
//just print to stdout for now
for (const char* c = begin; c < end; c++){
std::cout << *c;
}
}
};
class MyOStream : public std::basic_ostream< char, std::char_traits<char> >
{
public:
inline MyOStream(MyData data) :
std::basic_ostream< char, std::char_traits<char> >(&buf),
buf(data)
{
}
private:
MyBuffer buf;
};
int main(void)
{
MyData data;
MyOStream o(data);
for (int i = 0; i < 8; i++)
o << "hello world! ";
o << std::endl;
return 0;
}
स्रोत
2010-04-26 10:27:40
एसटीएल सरल हो सकता है, लेकिन यह सी ++ मानक पुस्तकालय का केवल एक हिस्सा है। आईओस्ट्रीम लाइब्रेरी के पास एसटीएल (एक बार क्या था) के साथ कुछ लेना देना नहीं है। एसटीएल मूल रूप से contianers + iterators + एल्गोरिदम है। Iostreams, लोकेशंस और सभी जिनमें एक पूरी तरह से अलग उत्पत्ति है, और आम तौर पर काम करने के लिए दर्द होता है;) – jalf