Created
September 13, 2016 23:03
-
-
Save vpetrigo/30d5065a5fa6995f154717d3d14850e8 to your computer and use it in GitHub Desktop.
Streambuf extending C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <streambuf> | |
#include <array> | |
#include <algorithm> | |
#include <iostream> | |
#include <sstream> | |
template <typename CharT> | |
class MyStreamBuf : public std::basic_streambuf<CharT> { | |
public: | |
using char_type = CharT; | |
using traits_type = typename std::basic_streambuf<CharT>::traits_type; | |
using int_type = typename traits_type::int_type; | |
MyStreamBuf() { | |
setg(&output_buf_.front(), &output_buf_.front(), &output_buf_.front()); | |
} | |
void str(const std::string& s) { | |
if (s.size() < output_buf_.size()) { | |
std::copy(s.cbegin(), s.cend(), output_buf_.begin()); | |
setg(&output_buf_.front(), &output_buf_.front(), &output_buf_.front() + s.size()); | |
} | |
else { | |
std::copy_n(s.cbegin(), output_buf_.size(), output_buf_.begin()); | |
setg(&output_buf_.front(), &output_buf_.front(), &output_buf_.back()); | |
} | |
} | |
protected: | |
int_type underflow() { | |
std::cout << "MyStreamBuf underflow!" << std::endl; | |
return traits_type::eof(); | |
} | |
private: | |
std::array<char_type, 128> output_buf_; | |
}; | |
using CMyStreamBuf = MyStreamBuf<char>; | |
int main() { | |
CMyStreamBuf msb; | |
const std::string s{ "Hello" }; | |
msb.str(s); | |
for (std::size_t i = 0; i < s.size() + 1; ++i) { | |
std::cout << static_cast<char> (msb.sbumpc()) << std::endl; | |
} | |
for (std::size_t i = 0; i < s.size(); ++i) { | |
std::cout << static_cast<char> (msb.sbumpc()) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment