]> git.tdb.fi Git - libs/core.git/blobdiff - source/strings/lexicalcast.h
Make lexical_cast symmetric
[libs/core.git] / source / strings / lexicalcast.h
index 3bfc342a1f584e91cc218eb24b226c7a29c777da..c6a17da3491d053b6460399fddea6473ea1ca839 100644 (file)
@@ -1,16 +1,9 @@
-/* $Id$
-
-This file is part of libmspstrings
-Copyright © 2006-2008 Mikko Rasa
-Distributed under the LGPL
-*/
-
 #ifndef MSP_STRINGS_LEXICALCAST_H_
 #define MSP_STRINGS_LEXICALCAST_H_
 
 #include <sstream>
 #include <string>
-#include <msp/core/except.h>
+#include <stdexcept>
 #include "fmt.h"
 
 namespace Msp {
@@ -18,10 +11,19 @@ namespace Msp {
 /**
 Thrown for errors in lexical conversions
 */
-class LexicalError: public Exception
+class lexical_error: public std::runtime_error
 {
 public:
-       LexicalError(const std::string &w_): Exception(w_) { }
+       lexical_error(const std::string &w): runtime_error(w) { }
+       virtual ~lexical_error() throw() { }
+};
+
+
+class format_mismatch: public lexical_error
+{
+public:
+       format_mismatch(const std::string &w): lexical_error(w) { }
+       virtual ~format_mismatch() throw() { }
 };
 
 
@@ -101,26 +103,54 @@ void operator>>(const LexicalConverter &c, T &v)
        ss.setf(std::ios_base::fmtflags(0), std::ios_base::skipws);
        ss>>v;
        if(ss.fail() || !ss.eof())
-               throw LexicalError("Conversion failure");
+               throw lexical_error("conversion failure");
 }
 
-// The main interface to the lexical conversion machinery
+// Helper struct to provide partial template specialization
+
+template<typename T, typename F>
+struct LexicalCast;
 
 template<typename T>
-inline T lexical_cast(const std::string &s, const Fmt &f = Fmt())
+struct LexicalCast<T, std::string>
 {
-       LexicalConverter conv(s, f);
-       T result;
-       conv>>result;
-       return result;
-}
+       static T cast(const std::string &s, const Fmt &f = Fmt())
+       {
+               LexicalConverter conv(s, f);
+               T result;
+               conv>>result;
+               return result;
+       }
+};
 
-template<typename T>
-inline std::string lexical_cast(const T &v, const Fmt &f = Fmt())
+template<typename F>
+struct LexicalCast<std::string, F>
+{
+       static std::string cast(const F &v, const Fmt &f = Fmt())
+       {
+               LexicalConverter conv(f);
+               conv<<v;
+               return conv.get();
+       }
+};
+
+template<>
+struct LexicalCast<std::string, std::string>
+{
+       static std::string cast(const std::string &v, const Fmt &f = Fmt())
+       {
+               LexicalConverter conv(f);
+               conv<<v;
+               return conv.get();
+       }
+};
+
+// The main interface to the lexical conversion machinery
+
+template<typename T, typename F>
+inline T lexical_cast(const F &v, const Fmt &f = Fmt())
 {
-       LexicalConverter conv(f);
-       conv<<v;
-       return conv.get();
+       return LexicalCast<T, F>::cast(v, f);
 }
 
 } // namespace Msp