]> git.tdb.fi Git - libs/core.git/blob - source/lexicalcast.h
b1e9db89b622361b2cd9798e6830c8de8daf3b39
[libs/core.git] / source / lexicalcast.h
1 #ifndef MSP_STRINGS_LEXICALCAST_H_
2 #define MSP_STRINGS_LEXICALCAST_H_
3
4 #include <sstream>
5 #include <string>
6 #include <msp/error.h>
7 #include "fmt.h"
8
9 namespace Msp {
10
11 class LexicalError: public Exception
12 {
13 public:
14         LexicalError(const std::string &w_): Exception(w_) { }
15 };
16
17 template<typename T>
18 T lexical_cast(const std::string &s)
19 {
20         std::istringstream ss(s);
21         ss.setf(std::ios_base::fmtflags(0), std::ios_base::skipws);
22
23         T tmp;
24         ss>>tmp;
25
26         if(ss.fail() || !ss.eof())
27                 throw LexicalError("Conversion failure");
28
29         return tmp;
30 }
31
32 template<typename T>
33 std::string lexical_cast(const T &v, const Fmt &f=Fmt())
34 {
35         std::ostringstream ss;
36         ss<<f<<v;
37         return ss.str();
38 }
39
40 } // namespace Msp
41
42 #endif