]> git.tdb.fi Git - libs/core.git/blob - source/lexicalcast.h
a2bb43953d43d764e24ff517d62e1ffd0052f6ee
[libs/core.git] / source / lexicalcast.h
1 /* $Id$
2
3 This file is part of libmspstrings
4 Copyright © 2006-2007 Mikko Rasa
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_STRINGS_LEXICALCAST_H_
9 #define MSP_STRINGS_LEXICALCAST_H_
10
11 #include <sstream>
12 #include <string>
13 #include <msp/core/except.h>
14 #include "fmt.h"
15
16 namespace Msp {
17
18 class LexicalError: public Exception
19 {
20 public:
21         LexicalError(const std::string &w_): Exception(w_) { }
22 };
23
24 template<typename T>
25 T lexical_cast(const std::string &s)
26 {
27         std::istringstream ss(s);
28         ss.setf(std::ios_base::fmtflags(0), std::ios_base::skipws);
29
30         T tmp;
31         ss>>tmp;
32
33         if(ss.fail() || !ss.eof())
34                 throw LexicalError("Conversion failure");
35
36         return tmp;
37 }
38
39 template<>
40 inline std::string lexical_cast<std::string>(const std::string &s)
41 {
42         return s;
43 }
44
45 template<typename T>
46 std::string lexical_cast(const T &v, const Fmt &f=Fmt())
47 {
48         std::ostringstream ss;
49         ss<<f<<v;
50         return ss.str();
51 }
52
53 } // namespace Msp
54
55 #endif