CatapultServer  v0.5.0.1 (Elephant)
Casting.h
Go to the documentation of this file.
1 
21 #pragma once
22 #include "catapult/exceptions.h"
23 #include <limits>
24 #include <stdexcept>
25 #include <type_traits>
26 
27 namespace catapult { namespace utils {
28 
30  template<typename T>
31  constexpr const T& as_const(T& ref) {
32  return ref;
33  }
34 
36  template<typename TEnum>
37  constexpr std::underlying_type_t<TEnum> to_underlying_type(TEnum value) {
38  return static_cast<std::underlying_type_t<TEnum>>(value);
39  }
40 
44  template<typename TSource, typename TDest>
45  TDest checked_cast(TSource value) {
46  using dest_limits = std::numeric_limits<TDest>;
47  using source_limits = std::numeric_limits<TSource>;
48  static_assert(
49  source_limits::min() < dest_limits::min() || source_limits::max() > dest_limits::max(),
50  "checked_cast can only be used when data truncation is possible");
51 
52  if (value < dest_limits::min() || value > dest_limits::max())
53  CATAPULT_THROW_RUNTIME_ERROR_1("checked_cast detected data truncation", value);
54 
55  return static_cast<TDest>(value);
56  }
57 }}
exceptions.h
catapult::utils::to_underlying_type
constexpr std::underlying_type_t< TEnum > to_underlying_type(TEnum value)
Converts a strongly typed enumeration value to its underlying integral value.
Definition: Casting.h:37
catapult::utils::as_const
constexpr const T & as_const(T &ref)
Coerces a reference (ref) to a const reference.
Definition: Casting.h:31
CATAPULT_THROW_RUNTIME_ERROR_1
#define CATAPULT_THROW_RUNTIME_ERROR_1(MESSAGE, PARAM1)
Macro used to throw a catapult runtime error with a single parameter.
Definition: exceptions.h:171
catapult
Definition: AddressExtractionExtension.cpp:28
catapult::utils::checked_cast
TDest checked_cast(TSource value)
Definition: Casting.h:45