///////////////////////////////////////////////////// // MT3Q2 - Convert from string to arbitrary type // // // // Jim Fawcett, CSE687 - OOD Midterm, Spring 2013 // ///////////////////////////////////////////////////// #include #include #include "../MTutility/MTutility.h" template T FromString(const std::string& str) { std::istringstream in(str); T t; in >> t; if(!in.good() && !in.eof()) throw std::invalid_argument("Can't convert string to instance of T"); return t; } int main() { Title("MT3Q2 - Converting from String to arbitrary type"); try { double d = FromString("3.14159265"); std::cout << "\n value of " << typeid(d).name() << " = " << d; int i = FromString("10"); std::cout << "\n value of " << typeid(i).name() << " = " << i; int foobar = FromString("foobar"); } catch(std::exception& ex) { std::cout << "\n " << ex.what() << "\n\n"; } std::cout << "\n\n"; return 0; }