1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <chrono>
#include <thread>
#include <iostream>
#include <streambuf>
template <typename C,
typename T = std::char_traits<C>>
class my_basic_streambuf
: public std::basic_streambuf<C, T>
{
using base_type = std::basic_streambuf<C, T>;
base_type* managed_sb;
my_basic_streambuf(std::basic_streambuf<C, T>* psb)
: managed_sb(psb)
{}
public:
template <typename C, typename T> friend class slow_stream;
public:
using
typename base_type::traits_type,
typename base_type::char_type,
typename base_type::int_type,
typename base_type::off_type,
typename base_type::pos_type;
int_type overflow(int_type c) override
{
auto const eof = traits_type::eof();
if (!traits_type::eq_int_type(c, eof))
{
std::this_thread::sleep_for(std::chrono::milliseconds{ 100 });
if (! traits_type::eq_int_type(managed_sb->sputc(c), eof))
{
managed_sb->pubsync();
return c;
}
else return eof;
}
else return traits_type::not_eof(c);
}
};
template <typename C, typename T>
class slow_stream
{
std::ostream& os;
my_basic_streambuf<C, T> new_sb;
std::streambuf* old_sb;
public:
explicit slow_stream(std::basic_ostream<C, T>& os)
: new_sb{ os.rdbuf() }, os{os}, old_sb{os.rdbuf(&new_sb)}
{}
slow_stream(slow_stream const&) = delete;
slow_stream(slow_stream&&) noexcept = delete;
slow_stream& operator=(slow_stream const&) = delete;
slow_stream& operator=(slow_stream&&) noexcept = delete;
~slow_stream()
{
os.rdbuf(old_sb);
}
};
int main()
{
{
slow_stream ss{ std::cout };
std::cout << "slow slow slow slow slow" << ' ' << 12345678 << '\n';
}
std::cout << "normal speed\n";
{
slow_stream ss{ std::cout };
std::cout << "slow slow slow slow slow" << ' ' << 87654321 << '\n';
}
}
| |