forked from mapsme/omim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecked_cast.hpp
43 lines (35 loc) · 1.5 KB
/
checked_cast.hpp
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
39
40
41
42
43
#pragma once
#include "base/assert.hpp"
#include <limits>
#include <type_traits>
namespace base
{
template <typename ReturnType, typename ParameterType>
ReturnType checked_cast(ParameterType v)
{
static_assert(std::is_integral<ParameterType>::value, "ParameterType should be integral");
static_assert(std::is_integral<ReturnType>::value, "ReturnType should be integral");
ReturnType const result = static_cast<ReturnType>(v);
CHECK_EQUAL(static_cast<ParameterType>(result), v, ());
CHECK((result > 0) == (v > 0), ("checked_cast failed, value =", v, ", result =", result));
return result;
}
template <typename ReturnType, typename ParameterType>
ReturnType asserted_cast(ParameterType v)
{
static_assert(std::is_integral<ParameterType>::value, "ParameterType should be integral");
static_assert(std::is_integral<ReturnType>::value, "ReturnType should be integral");
ReturnType const result = static_cast<ReturnType>(v);
ASSERT_EQUAL(static_cast<ParameterType>(result), v, ());
ASSERT((result > 0) == (v > 0), ("asserted_cast failed, value =", v, ", result =", result));
return result;
}
template <typename ResultType, typename ParameterType>
bool IsCastValid(ParameterType v)
{
static_assert(std::is_integral<ParameterType>::value, "ParameterType should be integral");
static_assert(std::is_integral<ResultType>::value, "ReturnType should be integral");
auto const result = static_cast<ResultType>(v);
return static_cast<ParameterType>(result) == v && ((result > 0) == (v > 0));
}
} // namespace base