[cig-commits] r8931 - cs/benchmark/cigma/trunk/src

luis at geodynamics.org luis at geodynamics.org
Wed Dec 19 12:04:44 PST 2007


Author: luis
Date: 2007-12-19 12:04:43 -0800 (Wed, 19 Dec 2007)
New Revision: 8931

Added:
   cs/benchmark/cigma/trunk/src/convert.h
Log:
Template functions for conversion to/from string

Added: cs/benchmark/cigma/trunk/src/convert.h
===================================================================
--- cs/benchmark/cigma/trunk/src/convert.h	2007-12-19 20:04:36 UTC (rev 8930)
+++ cs/benchmark/cigma/trunk/src/convert.h	2007-12-19 20:04:43 UTC (rev 8931)
@@ -0,0 +1,48 @@
+#ifndef __CONVERT_H__
+#define __CONVERT_H__
+
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <typeinfo>
+#include <stdexcept>
+
+class BadConversion : public std::runtime_error
+{
+public:
+    BadConversion(const std::string& s) : std::runtime_error(s) {}
+};
+
+template <typename T>
+inline std::string stringify(const T& x)
+{
+    std::ostringstream o;
+    if (!(o << x))
+    {
+        throw BadConversion(std::string("stringify(") + typeid(x).name() + ")");
+    }
+    return o.str();
+}
+
+template <typename T>
+inline void convert(const std::string& s, T& x,
+                    bool failIfLeftOverChars = true)
+{
+    std::istringstream i(s);
+    char c;
+    if (!(i >> x) || (failIfLeftOverChars && i.get(c)))
+    {
+        throw BadConversion(s);
+    }
+}
+
+template <typename T>
+inline T convertTo(const std::string& s,
+                   bool failIfLeftOverChars = true)
+{
+    T x;
+    convert(s, x, failIfLeftOverChars);
+    return x;
+}
+
+#endif



More information about the cig-commits mailing list