bit_cast.hpp
Go to the documentation of this file.
1 // Copyright (C) 2020-2023 Jonathan Müller and lexy contributors
2 // SPDX-License-Identifier: BSL-1.0
3 
4 #ifndef LEXY_CALLBACK_BIT_CAST_HPP_INCLUDED
5 #define LEXY_CALLBACK_BIT_CAST_HPP_INCLUDED
6 
7 #include <lexy/callback/base.hpp>
8 
9 #ifndef LEXY_HAS_BITCAST
10 # if defined(__has_builtin)
11 # if __has_builtin(__builtin_bit_cast)
12 # define LEXY_HAS_BITCAST 2
13 # endif
14 # endif
15 #endif
16 
17 #ifndef LEXY_HAS_BITCAST
18 # if defined(__has_include)
19 # if __has_include(<bit>)
20 # include <bit>
21 # ifdef __cpp_lib_bit_cast
22 # define LEXY_HAS_BITCAST 1
23 # endif
24 # endif
25 # endif
26 #endif
27 
28 #ifndef LEXY_HAS_BITCAST
29 # define LEXY_HAS_BITCAST 0
30 #endif
31 
32 #if LEXY_HAS_BITCAST == 2
33 # define LEXY_BITCAST_CONSTEXPR constexpr
34 #elif LEXY_HAS_BITCAST == 1
35 # define LEXY_BITCAST_CONSTEXPR constexpr
36 #else
37 # include <cstring>
38 # define LEXY_BITCAST_CONSTEXPR
39 #endif
40 
41 namespace lexy
42 {
43 template <typename T>
44 struct _bit_cast
45 {
46  static_assert(std::is_trivially_copyable_v<T>);
47 
48  using return_type = T;
49 
50  template <typename Arg, typename = std::enable_if_t<sizeof(T) == sizeof(Arg)
51  && std::is_trivially_copyable_v<Arg>>>
52  LEXY_BITCAST_CONSTEXPR T operator()(const Arg& arg) const
53  {
54 #if LEXY_HAS_BITCAST == 2
55 
56  return __builtin_bit_cast(T, arg);
57 
58 #elif LEXY_HAS_BITCAST == 1
59 
60  return std::bit_cast<T>(arg);
61 
62 #else
63 
64  static_assert(std::is_default_constructible_v<T>, "sorry, get a better standard library");
65 
66  T to;
67  std::memcpy(&to, &arg, sizeof(T));
68  return to;
69 
70 #endif
71  }
72 };
73 
75 template <typename T>
76 constexpr auto bit_cast = _bit_cast<T>{};
77 } // namespace lexy
78 
79 #endif // LEXY_CALLBACK_BIT_CAST_HPP_INCLUDED
80 
base.hpp
lexy::bit_cast
constexpr auto bit_cast
std::bit_cast as a callback.
Definition: bit_cast.hpp:76
lexy
Definition: any_ref.hpp:12
lexy::_bit_cast
Definition: bit_cast.hpp:44
LEXY_BITCAST_CONSTEXPR
#define LEXY_BITCAST_CONSTEXPR
Definition: bit_cast.hpp:38
lexy::_bit_cast::operator()
LEXY_BITCAST_CONSTEXPR T operator()(const Arg &arg) const
Definition: bit_cast.hpp:52
detail::enable_if_t
typename std::enable_if< B, T >::type enable_if_t
Definition: json.hpp:3095
lexy::_bit_cast::return_type
T return_type
Definition: bit_cast.hpp:48


behaviortree_cpp_v4
Author(s): Davide Faconti
autogenerated on Fri Jun 28 2024 02:20:07