#ifndef LIBUTILS_H #define LIBUTILS_H /////////////////////////////////////////////////////////////////// // LibUtils.h - utility functions and classes for all libraries // // ver 1.0 // // ------------------------------------------------------------- // // copyright © Jim Fawcett, 2012 // // All rights granted provided that this notice is retained // // ------------------------------------------------------------- // // Jim Fawcett, CST 4-187, Syracuse University, 315 443 3948 // // Summer Projects, 2012 // // Win7, Visual Studio 2010 // /////////////////////////////////////////////////////////////////// /* * Package Operations: * =================== * This package provides classes: * - Assert * - SearchableStack * And the functions: * - fromString * - toString */ #include #include #include #include #include namespace LibUtils { //----< assert that throws instead of aborting >----------------- template class Assert { public: static void is(bool predicate, const std::string& msg="") { std::string seperator; if(msg.size() > 0) seperator = ": "; else seperator = ""; if(predicate == false) { std::string msgOut = std::string(typeid(T).name()) + seperator + msg; throw T(msgOut); } } }; template <> class Assert { public: static void is(bool predicate, const std::string& msg="") { if(predicate == false) { if(msg.size() == 0) throw std::exception(); throw std::runtime_error(msg); } } }; //----< generic conversion from string to T >-------------------- template inline T fromString(const std::string& s, std::streamsize prec=8) { std::istringstream temp(s); T t; temp.precision(prec); temp >> t; return t; } //----< generic conversion from T to string >-------------------- template inline std::string toString(const T& t, std::streamsize prec=8) { std::ostringstream temp; temp.precision(prec); temp << t; return temp.str(); } //----< stack that can be indexed >------------------------------ template class SearchableStack { public: void push(const T& t) { stack.push_back(t); } T pop() { T t = stack.back(); stack.pop_back(); return t; } T& top() { return stack.back(); } size_t size() { return stack.size(); } bool contains(const T& t) { for(size_t i=0; i stack; }; } #endif