2018-07-15 13:26:44 +02:00
|
|
|
#ifndef _LIBRW_CASTS_HPP_
|
|
|
|
#define _LIBRW_CASTS_HPP_
|
|
|
|
|
|
|
|
#include <cstring> // memcpy
|
2018-08-14 20:46:47 +02:00
|
|
|
#include <string>
|
2018-07-15 13:26:44 +02:00
|
|
|
|
|
|
|
#include "rw/debug.hpp"
|
|
|
|
|
|
|
|
//Based on https://gist.github.com/socantre/3472964
|
|
|
|
template <class Dest, class Source>
|
|
|
|
inline Dest bit_cast(Source const &source) {
|
2018-08-29 22:46:00 +02:00
|
|
|
Dest dest;
|
2018-07-15 13:26:44 +02:00
|
|
|
std::memcpy(&dest, &source, sizeof(Dest));
|
|
|
|
return dest;
|
|
|
|
}
|
|
|
|
|
|
|
|
template <class T, class S>
|
|
|
|
inline T lexical_cast(const S& s);
|
|
|
|
|
2018-08-06 21:45:40 +02:00
|
|
|
template <class T, class S>
|
2018-08-29 22:46:00 +02:00
|
|
|
inline T lexical_cast(const S& s, int base);
|
2018-08-06 21:45:40 +02:00
|
|
|
|
2018-07-15 13:26:44 +02:00
|
|
|
template <>
|
2018-08-29 22:46:00 +02:00
|
|
|
inline int lexical_cast(const std::string& source, int base) {
|
2018-07-15 13:26:44 +02:00
|
|
|
char* end = nullptr; //for errors handling
|
2018-08-06 21:45:40 +02:00
|
|
|
int result = std::strtol(source.c_str(), &end, base);
|
2018-07-15 13:26:44 +02:00
|
|
|
RW_CHECK(end != source.c_str(), "Problem with conversion " << *end << " to int");
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2018-08-06 21:45:40 +02:00
|
|
|
template <>
|
|
|
|
inline int lexical_cast(const std::string& source) {
|
|
|
|
return lexical_cast<int>(source, 10);
|
|
|
|
}
|
|
|
|
|
2018-07-15 15:55:41 +02:00
|
|
|
template <>
|
|
|
|
inline float lexical_cast(const std::string& source) {
|
|
|
|
char* end = nullptr; //for errors handling
|
|
|
|
float result = std::strtof(source.c_str(), &end);
|
|
|
|
RW_CHECK(end != source.c_str(), "Problem with conversion " << *end << " to float");
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2018-07-15 13:26:44 +02:00
|
|
|
#endif
|