]> git.tdb.fi Git - libs/core.git/blob - source/lexicalcast.h
c73856b8228894374f00b97e2f81dcbcd4532ca2
[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/error.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<typename T>
40 std::string lexical_cast(const T &v, const Fmt &f=Fmt())
41 {
42         std::ostringstream ss;
43         ss<<f<<v;
44         return ss.str();
45 }
46
47 } // namespace Msp
48
49 #endif