LIPH's C++ Codes
casts.h
Go to the documentation of this file.
1#ifndef LIPH_LANG_CASTS_H_
2#define LIPH_LANG_CASTS_H_
3
4#include <cassert>
5#include <cstring>
6#include <type_traits>
7
8namespace liph {
9
10template <typename To, typename From>
11inline To implicit_cast(const From& f) {
12 return f;
13}
14
15template <typename To, typename From>
16inline To down_cast(From *f) {
17 if (false) {
18 implicit_cast<From *, To>(0);
19 }
20#if !defined(NDEBUG)
21 assert(f == nullptr || dynamic_cast<To>(f) != nullptr);
22#endif
23 return static_cast<To>(f);
24}
25
26template <typename To, typename From>
27inline To down_cast(From& f) {
28 using Pointer = typename std::remove_reference<To>::type *;
29 if (false) {
30 implicit_cast<From *, Pointer>(0);
31 }
32#if !defined(NDEBUG)
33 assert(dynamic_cast<Pointer>(&f) != nullptr);
34#endif
35 return *static_cast<Pointer>(&f);
36}
37
38template <typename To, typename From>
39inline To bit_cast(const From& from) {
40 static_assert(sizeof(From) == sizeof(To), "bit_cast_with_different_sizes");
41 To dest;
42 memcpy(&dest, &from, sizeof(dest));
43 return dest;
44}
45
46} // namespace liph
47
48#endif // LIPH_LANG_CASTS_H_
Definition: algorithm.h:10
To bit_cast(const From &from)
Definition: casts.h:39
To down_cast(From *f)
Definition: casts.h:16
To implicit_cast(const From &f)
Definition: casts.h:11