Skip to content

Instantly share code, notes, and snippets.

@alexgeek
Created November 25, 2022 10:59
Show Gist options
  • Select an option

  • Save alexgeek/e39e0aeeac2f5e4b08efc62e7bf10bb9 to your computer and use it in GitHub Desktop.

Select an option

Save alexgeek/e39e0aeeac2f5e4b08efc62e7bf10bb9 to your computer and use it in GitHub Desktop.
Hooks into any writes to the given ostream.
#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