GCS  0.2.3
gu_convert.hpp
1 // Copyright (C) 2009 Codership Oy <info@codership.com>
2 
9 #ifndef _gu_convert_hpp_
10 #define _gu_convert_hpp_
11 
12 #include "gu_macros.h"
13 #include "gu_throw.hpp"
14 #include <limits>
15 
16 namespace gu
17 {
26  template <typename FROM, typename TO> inline
27  TO convert (const FROM& from, const TO& to)
28  {
29  if (gu_unlikely(from > std::numeric_limits<TO>::max() ||
30  from < std::numeric_limits<TO>::min()))
31  {
32  // @todo: figure out how to print type name without RTTI
33  gu_throw_error (ERANGE) << from << " is unrepresentable with "
34  << (std::numeric_limits<TO>::is_signed ?
35  "signed" : "unsigned") << " "
36  << sizeof(TO) << " bytes.";
37  }
38 
39  return static_cast<TO>(from);
40  }
41 
42  /* Specialized templates are for signed conversion */
43 
44  template <> inline
45  long long convert (const unsigned long long& from, const long long& to)
46  {
47  if (gu_unlikely(from > static_cast<unsigned long long>
48  (std::numeric_limits<long long>::max())))
49  {
50  gu_throw_error (ERANGE) << from
51  << " is unrepresentable with 'long long'";
52  }
53 
54  return static_cast<long long>(from);
55  }
56 
57  template <> inline
58  unsigned long long convert (const long long& from,
59  const unsigned long long& to)
60  {
61  if (gu_unlikely(from < 0))
62  {
63  gu_throw_error (ERANGE) << from
64  << " is unrepresentable with 'unsigned long long'";
65  }
66 
67  return static_cast<unsigned long long>(from);
68  }
69 
70  template <> inline
71  long convert (const unsigned long& from, const long& to)
72  {
73  if (gu_unlikely(from > static_cast<unsigned long>
74  (std::numeric_limits<long>::max())))
75  {
76  gu_throw_error (ERANGE) << from
77  << " is unrepresentable with 'long'";
78  }
79 
80  return static_cast<long long>(from);
81  }
82 
83  template <> inline
84  unsigned long convert (const long& from, const unsigned long& to)
85  {
86  if (gu_unlikely(from < 0))
87  {
88  gu_throw_error (ERANGE) << from
89  << " is unrepresentable with 'unsigned long'";
90  }
91 
92  return static_cast<unsigned long>(from);
93  }
94 
95  template <> inline
96  int convert (const unsigned int& from, const int& to)
97  {
98  if (gu_unlikely(from > static_cast<unsigned int>
99  (std::numeric_limits<int>::max())))
100  {
101  gu_throw_error (ERANGE) << from
102  << " is unrepresentable with 'long'";
103  }
104 
105  return static_cast<int>(from);
106  }
107 
108  template <> inline
109  unsigned int convert (const int& from, const unsigned int& to)
110  {
111  if (gu_unlikely(from < 0))
112  {
113  gu_throw_error (ERANGE) << from
114  << " is unrepresentable with 'unsigned long'";
115  }
116 
117  return static_cast<unsigned int>(from);
118  }
119 }
120 
121 #endif /* _gu_convert_hpp_ */
TO convert(const FROM &from, const TO &to)
Definition: gu_convert.hpp:27