mycpu/cmem.h

00001 
00008 #ifndef CMEM_H
00009 #define CMEM_H 1
00010 
00011 #include <vector>
00012 #include <istream>
00013 #include <sstream>
00014 #include <stdexcept>
00015 #ifdef DEBUG
00016 # include <iostream>
00017 # include <iomanip>
00018 #endif
00019 
00025 class CMemError
00026  : public std::invalid_argument
00027 {
00028   public:
00039     CMemError(const std::string& what)
00040       : std::invalid_argument(what)
00041     {}
00042 };
00043 
00049 template <class T>
00050 class CMem
00051   : public std::vector<T>
00052 {
00053   typedef std::vector<T> super;
00054   typedef typename super::iterator iterator;
00055   using super::size;
00056   using super::begin;
00057   using super::end;
00058 
00059   public:
00072     void initialize(std::istream& in, T& datatype)
00073     {
00074       if (!in.good())
00075         return;
00076 
00077       std::string line;
00078       unsigned i = 0;
00079       while (!in.eof() && in.good())
00080       {
00081         ++i;
00082         std::getline(in, line);
00083 
00084         /* skip last line if it's empty */
00085         if (line.empty() && in.eof())
00086           break;
00087 
00088         T value(datatype);
00089         if (!line.empty())
00090         {
00091           /* simple boost::lexical_cast replacement */
00092           std::stringstream interpreter;
00093           if(!(interpreter << line && interpreter >> value && interpreter.get() == std::char_traits<char>::eof()))
00094           {
00095             std::stringstream sstr;
00096             sstr << "Unable to convert input (line " << i << ") to datatype";
00097             throw CMemError(sstr.str());
00098           }
00099         }
00100 
00101         push_back(value);
00102       }
00103     }
00104 
00105 #if DEBUG
00106 
00116     void dump(std::ostream& out)
00117     {
00118       out << "[MEMORY DUMP]" << std::endl;
00119       unsigned i = 0;
00120       for(iterator it = begin(); it != end(); ++it)
00121       {
00122         out << "[" << std::setw(4) << std::setfill('0') << i << "]  "
00123             << *it << std::endl;
00124         ++i;
00125       }
00126     }
00127 #endif
00128 };
00129 
00130 #endif
00131 
00132 /* vim: set et sw=2 ts=2: */

Generated on Sat May 30 16:32:35 2009 for mycpu by  doxygen 1.5.3