ios_state.h

Go to the documentation of this file.
00001 ///
00002 /// \file       ios_state.h
00003 ///             RAII class to save and restore iostream state
00004 ///
00005 
00006 /*
00007     Copyright (C) 2011-2012, Net Direct Inc. (http://www.netdirect.ca/)
00008 
00009     This program is free software; you can redistribute it and/or modify
00010     it under the terms of the GNU General Public License as published by
00011     the Free Software Foundation; either version 2 of the License, or
00012     (at your option) any later version.
00013 
00014     This program is distributed in the hope that it will be useful,
00015     but WITHOUT ANY WARRANTY; without even the implied warranty of
00016     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00017 
00018     See the GNU General Public License in the COPYING file at the
00019     root directory of this project for more details.
00020 */
00021 
00022 #ifndef __BARRY_IOS_STATE_H__
00023 #define __BARRY_IOS_STATE_H__
00024 
00025 #include <ios>
00026 #include <ostream>
00027 
00028 namespace Barry {
00029 
00030 //
00031 // ios_format_state
00032 //
00033 /// This class saves the following stream settings:
00034 ///     - flags
00035 ///     - precision
00036 ///     - width
00037 ///     - fill character
00038 ///
00039 /// and restores them in the destructor.
00040 ///
00041 class ios_format_state
00042 {
00043 public:
00044         typedef std::ios                stream_type;
00045 
00046 private:
00047         stream_type                     &m_stream;
00048         std::ios_base::fmtflags         m_flags;
00049         std::streamsize                 m_precision;
00050         std::streamsize                 m_width;
00051         stream_type::char_type          m_fill;
00052 
00053 public:
00054         explicit ios_format_state(stream_type &stream)
00055                 : m_stream(stream)
00056                 , m_flags(stream.flags())
00057                 , m_precision(stream.precision())
00058                 , m_width(stream.width())
00059                 , m_fill(stream.fill())
00060         {
00061         }
00062 
00063         ~ios_format_state()
00064         {
00065                 restore();
00066         }
00067 
00068         void restore()
00069         {
00070                 m_stream.flags(m_flags);
00071                 m_stream.precision(m_precision);
00072                 m_stream.width(m_width);
00073                 m_stream.fill(m_fill);
00074         }
00075 };
00076 
00077 }
00078 
00079 #endif
00080