Created
November 25, 2022 10:59
-
-
Save alexgeek/e39e0aeeac2f5e4b08efc62e7bf10bb9 to your computer and use it in GitHub Desktop.
Hooks into any writes to the given ostream.
This file contains hidden or 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 <functional> | |
| #include <streambuf> | |
| #include <iostream> | |
| /** | |
| * \brief Hooks into any writes to the given ostream. | |
| * \tparam Duplicate If duplicate is true then it will pass through to the original stream. | |
| */ | |
| template<bool Duplicate> | |
| class callback_streambuf final : public std::streambuf | |
| { | |
| public: | |
| callback_streambuf(std::ostream& stream, std::function<void(const char_type*, std::streamsize)> callback) | |
| : callback(callback) | |
| , parent (stream.rdbuf(this)) | |
| , stream(stream) | |
| { | |
| } | |
| virtual ~callback_streambuf() | |
| { | |
| stream.rdbuf(parent); | |
| } | |
| protected: | |
| std::streamsize xsputn(char_type const* s, std::streamsize count) | |
| { | |
| callback(s, count); | |
| if constexpr (Duplicate) | |
| parent->sputn(s, count); | |
| return count; | |
| } | |
| private: | |
| std::function<void(const char_type*, std::streamsize)> callback; | |
| std::streambuf* parent; | |
| std::ostream& stream; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment