-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstring_convert.h
38 lines (32 loc) · 903 Bytes
/
string_convert.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#pragma once
#include <sstream>
#include <string>
template<class T>
std::string to_string(const T& t) {
std::ostringstream os;
os << t;
return os.str();
}
// class for reporting string cast errors
struct bad_from_string : std::bad_cast {
const char* what() const noexcept override {
return "bad cast from string";
}
};
template<class T>
T from_string(const std::string& s) {
std::istringstream is(s);
T t;
if (!(is >> t)) throw bad_from_string();
return t;
}
template<class Target, class Source>
Target to(Source source) {
std::stringstream interpreter;
Target target;
if (!(interpreter << source) // write source into stream
|| !(interpreter >> target) // read target from stream
|| !(interpreter >> std::ws).eof()) // stuff left in stream?
throw std::bad_cast();
return target;
}