Welcome to mirror list, hosted at ThFree Co, Russian Federation.

checked_cast.hpp « base - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bc37f134183857be4132443d77d9170d46aba1f2 (plain)
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
#pragma once

#include "base/assert.hpp"

#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;
}
}  // namespace base