Demo

#include "namespace.h"

int main(void)
{
   dBug::dump() << "You should see me " << std::endl;
   dBug::pause();
   dBug::dump() << "You should NOT see me " << std::endl;
}

Header

#ifndef DEFINE_DEBUG_DUMP_DEF
#define DEFINE_DEBUG_DUMP_DEF

#include <sstream>
#include <iostream>
#include <fstream>

namespace dBug
{
    /* streambuf impl that does nothing so we can
     *  shunt output to nowhere
     */
    class NullBuf : public std::streambuf
    {
    public:
       NullBuf(int size) { }

    private:
       int overflow(int c) { return c; }
       int sync()          { return 0; }
    };

    class DumpMgr
    {
    public:
        static DumpMgr& instance()
        {   static DumpMgr the_mgr;
            return the_mgr;
        }

        std::ostream& dump_it(bool file = false, bool force = false);

        void pause(bool pauseIt = true);

    private:
    /* hide xtor, dtor, copy xtor, assignment operator to keep
     *  singleton to be well-behaved
     */
        DumpMgr();
        ~DumpMgr();
        DumpMgr(DumpMgr&);
        DumpMgr& operator=(DumpMgr const&);

        bool skipDump;
        NullBuf* nb;

        std::ofstream file_out;
        std::ostream* null_stream;
    };

    std::ostream& dump(bool file = false, bool force = false);
    void pause(bool reallyPause = true);
}
#endif

CPP file

#include <sstream>
#include "namespace.h"

namespace dBug
{
    DumpMgr::DumpMgr()
    {   skipDump = false;
        nb = new NullBuf(0);
        null_stream = new std::ostream(nb);

        file_out.open("debug.out");
    }

    DumpMgr::~DumpMgr()
    {   delete nb;
        delete null_stream;
    }

    void DumpMgr::pause(bool pauseIt)
    {   skipDump = pauseIt;
    }

    std::ostream& DumpMgr::dump_it(bool file, bool force)
    {
        if (skipDump && !force)
        {   return *null_stream;
        }
        if (file)
        {   return file_out;
        }
        else
        {   return std::cout;
        }
    }

    /* publicly-available stuff interface
     */
    DumpMgr* the_DumpMgr;

    std::ostream& dump(bool file, bool force)
    {   DumpMgr::instance().dump_it(file, force);
    }

    void pause(bool reallyPause) { DumpMgr::instance().pause(reallyPause); }

-- MattWalsh - 09 May 2009

Topic revision: r2 - 11 May 2009 - MattWalsh
 
This site is powered by the TWiki collaboration platformCopyright © 2008-2012 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback