Skip to content

Instantly share code, notes, and snippets.

@hotwatermorning
Last active June 14, 2017 03:17
Show Gist options
  • Save hotwatermorning/7c6f8cb20c95e3280b52c575f4616bb6 to your computer and use it in GitHub Desktop.
Save hotwatermorning/7c6f8cb20c95e3280b52c575f4616bb6 to your computer and use it in GitHub Desktop.
enable_output_to_visual_studio
#if defined(_MSC_VER)
//! @file
/*! std::cout, std::wcerrなどのストリームへの出力を、DebugOutputString()に流して、
* Visual Studioの出力ウィンドウに出力できるようにする。
* (DebugOutputString()への出力はリリースモードでも有効であることに注意すること)
* 参考: http://fa11enprince.hatenablog.com/entry/2015/07/04/192645
* 参考: http://blog.livedoor.jp/tek_nishi/archives/5004322.html
*/
#include <iostream>
#include <cassert>
#include <windows.h>
namespace hwm {
template<class CharType>
struct debug_output_streambuf : public std::basic_streambuf<CharType>
{
public:
virtual int_type overflow(int_type c) override
{
if(c != EOF) {
char_type const buf[] = { c, (CharType)0 };
Output(buf);
}
return c;
}
private:
void Output(char const *buf) { OutputDebugStringA(buf); }
void Output(wchar_t const *buf) { OutputDebugStringW(buf); }
};
//! このクラスのインスタンスを作成すると、そのスコープ内でのstd::cout, std::wcerrなどへの出力はDebugOutputString()へ流されるようになる。
class enable_output_to_visual_studio
{
template<class StreamType>
struct Impl
{
debug_output_streambuf<typename StreamType::char_type> debug_streambuf_;
std::basic_streambuf<typename StreamType::char_type> *prev_streambuf_;
StreamType *stream_;
Impl(StreamType &stream)
{
stream_ = &stream;
prev_streambuf_ = stream_->rdbuf(&debug_streambuf_);
}
~Impl()
{
assert(stream_->rdbuf() == prev_streambuf_);
stream_->rdbuf(prev_streambuf_);
}
};
private:
Impl<std::ostream> cout_;
Impl<std::ostream> clog_;
Impl<std::ostream> cerr_;
Impl<std::wostream> wcout_;
Impl<std::wostream> wclog_;
Impl<std::wostream> wcerr_;
public:
enable_output_to_visual_studio()
: cout_(std::cout)
, clog_(std::clog)
, cerr_(std::cerr)
, wcout_(std::wcout)
, wclog_(std::wclog)
, wcerr_(std::wcerr)
{}
};
} // namespace hwm
#endif // defined(_MSC_VER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment