C++ 流重定向输出到调试

本文介绍了一个使用C++实现的调试输出类,该类利用模板技术为字符和宽字符提供调试信息输出功能。通过继承标准字符串缓冲区并重写析构函数与sync方法,在程序结束时将调试信息输出到Windows环境中。
#include <Windows.h>
#include <ostream>
#include <sstream>
#include <string>
//using namespace std;

template < class CharT, class TraintT = std::char_traits<CharT> > 
class basic_debugbuf : public std::basic_stringbuf <CharT, TraintT>
{
    ~basic_debugbuf()
    {
        sync();
    }

protected:
    int sync()
    {
        WriteDebugString(str().c_str());
        str(std::basic_string<CharT>());    

        return 0;
    }

    void WriteDebugString(const CharT * msg)  {}
};

template <>
void basic_debugbuf<char>::WriteDebugString(const char *msg)
{
    ::OutputDebugStringA(msg);
}

template<>
void basic_debugbuf<wchar_t>::WriteDebugString(const wchar_t *msg)
{
    ::OutputDebugStringW(msg);
}

template< class CharT, class TraistT = std::char_traits< CharT> >
class basic_debugostream : public std::basic_ostream < CharT, TraistT>
{
public:
    basic_debugostream() : std::basic_ostream < CharT, TraistT> (new basic_debugbuf<CharT, TraistT> ()) {}
    ~basic_debugostream() { delete rdbuf(); }
};

typedef basic_debugostream<char> DebugStream;
typedef basic_debugostream<wchar_t> WDebugStream;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值