Skip to content

Instantly share code, notes, and snippets.

@kalineh
Created February 4, 2013 10:39
Show Gist options
  • Save kalineh/4706078 to your computer and use it in GitHub Desktop.
Save kalineh/4706078 to your computer and use it in GitHub Desktop.
//
// debug_stringbuf.h
//
// put this somewhere during init:
//
// debug_stringbuf_init();
//
#pragma once
#include <ostream>
#include <sstream>
#include <string>
extern void debug_stringbuf_init() ;
extern void debug_stringbuf_output(const char* text) ;
extern void debug_stringbuf_outputw(const wchar_t* text);
template <class CharT, class TraitsT = std::char_traits<CharT> >
class debug_stringbuf : public std::basic_stringbuf<CharT, TraitsT>
{
public:
virtual ~debug_stringbuf()
{
sync();
}
private:
virtual int sync()
{
write(str().c_str());
str(std::basic_string<CharT>());
return 0;
}
void write(const CharT *text) {}
};
template<> void debug_stringbuf<char>::write(const char *text) { debug_stringbuf_output(text); }
template<> void debug_stringbuf<wchar_t>::write(const wchar_t *text) { debug_stringbuf_outputw(text); }
template<class CharT, class TraitsT = std::char_traits<CharT> >
class debug_ostream : public std::basic_ostream<CharT, TraitsT>
{
public:
debug_ostream()
: std::basic_ostream<CharT, TraitsT>(new debug_stringbuf<CharT, TraitsT>())
{
}
~debug_ostream()
{
delete rdbuf();
}
};
typedef debug_ostream<char> dostream;
typedef debug_ostream<wchar_t> wdostream;
//
// debug_stringbuf.cpp
//
#include "debug_stringbuf.h"
#include <Windows.h>
#include <iostream>
void debug_stringbuf_init()
{
static dostream redirect_stream;
std::cout.rdbuf(redirect_stream.rdbuf());
std::cerr.rdbuf(redirect_stream.rdbuf());
}
void debug_stringbuf_output(const char* text)
{
::OutputDebugStringA(text);
}
void debug_stringbuf_outputw(const wchar_t* text)
{
::OutputDebugStringW(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment