/////////////////////////////////////////////////////////////////////////// // convert.cpp - functions that convert type values to strings and back // // Exam4:Q5 // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2005 // /////////////////////////////////////////////////////////////////////////// #include #include #include template std::string convert(const T& t) { std::ostringstream os; os << t; if(!os.good()) { std::string msg = "can't convert "; msg.append(typeid(T).name()); throw std::invalid_argument(msg.c_str()); } return os.str(); } template T convert(const std::string& s) { std::istringstream is(s); T t; is.seekg(std::ios::beg); is >> t; if(!is.good() && !is.eof()) { std::string msg = "can't convert "; msg.append(s); throw std::invalid_argument(msg.c_str()); } return t; } class foobar { } foo; void main() { std::cout << "\n successfully converted " << 3.1415927 << " to \"" << convert(3.1415927).c_str() << "\""; std::cout << "\n successfully converted " << "\"-17\"" << " to " << convert("-17"); std::cout << "\n\n"; //////////////////////////////////////////////// // fail to compile // // std::string ex = convert(foo); // convert("foobar"); try { convert("abc"); // throws exception } catch(exception& e) { std::cout << "\n " << e.what() << "\n\n"; } }