casts.h (7089B)
1 // 2 // Copyright 2017 The Abseil Authors. 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // https://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 // ----------------------------------------------------------------------------- 17 // File: casts.h 18 // ----------------------------------------------------------------------------- 19 // 20 // This header file defines casting templates to fit use cases not covered by 21 // the standard casts provided in the C++ standard. As with all cast operations, 22 // use these with caution and only if alternatives do not exist. 23 24 #ifndef ABSL_BASE_CASTS_H_ 25 #define ABSL_BASE_CASTS_H_ 26 27 #include <cstring> 28 #include <memory> 29 #include <type_traits> 30 #include <utility> 31 32 #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L 33 #include <bit> // For std::bit_cast. 34 #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L 35 36 #include "absl/base/internal/identity.h" 37 #include "absl/base/macros.h" 38 #include "absl/meta/type_traits.h" 39 40 namespace absl { 41 ABSL_NAMESPACE_BEGIN 42 43 // implicit_cast() 44 // 45 // Performs an implicit conversion between types following the language 46 // rules for implicit conversion; if an implicit conversion is otherwise 47 // allowed by the language in the given context, this function performs such an 48 // implicit conversion. 49 // 50 // Example: 51 // 52 // // If the context allows implicit conversion: 53 // From from; 54 // To to = from; 55 // 56 // // Such code can be replaced by: 57 // implicit_cast<To>(from); 58 // 59 // An `implicit_cast()` may also be used to annotate numeric type conversions 60 // that, although safe, may produce compiler warnings (such as `long` to `int`). 61 // Additionally, an `implicit_cast()` is also useful within return statements to 62 // indicate a specific implicit conversion is being undertaken. 63 // 64 // Example: 65 // 66 // return implicit_cast<double>(size_in_bytes) / capacity_; 67 // 68 // Annotating code with `implicit_cast()` allows you to explicitly select 69 // particular overloads and template instantiations, while providing a safer 70 // cast than `reinterpret_cast()` or `static_cast()`. 71 // 72 // Additionally, an `implicit_cast()` can be used to allow upcasting within a 73 // type hierarchy where incorrect use of `static_cast()` could accidentally 74 // allow downcasting. 75 // 76 // Finally, an `implicit_cast()` can be used to perform implicit conversions 77 // from unrelated types that otherwise couldn't be implicitly cast directly; 78 // C++ will normally only implicitly cast "one step" in such conversions. 79 // 80 // That is, if C is a type which can be implicitly converted to B, with B being 81 // a type that can be implicitly converted to A, an `implicit_cast()` can be 82 // used to convert C to B (which the compiler can then implicitly convert to A 83 // using language rules). 84 // 85 // Example: 86 // 87 // // Assume an object C is convertible to B, which is implicitly convertible 88 // // to A 89 // A a = implicit_cast<B>(C); 90 // 91 // Such implicit cast chaining may be useful within template logic. 92 template <typename To> 93 constexpr To implicit_cast(typename absl::internal::type_identity_t<To> to) { 94 return to; 95 } 96 97 // bit_cast() 98 // 99 // Creates a value of the new type `Dest` whose representation is the same as 100 // that of the argument, which is of (deduced) type `Source` (a "bitwise cast"; 101 // every bit in the value representation of the result is equal to the 102 // corresponding bit in the object representation of the source). Source and 103 // destination types must be of the same size, and both types must be trivially 104 // copyable. 105 // 106 // As with most casts, use with caution. A `bit_cast()` might be needed when you 107 // need to treat a value as the value of some other type, for example, to access 108 // the individual bits of an object which are not normally accessible through 109 // the object's type, such as for working with the binary representation of a 110 // floating point value: 111 // 112 // float f = 3.14159265358979; 113 // int i = bit_cast<int>(f); 114 // // i = 0x40490fdb 115 // 116 // Reinterpreting and accessing a value directly as a different type (as shown 117 // below) usually results in undefined behavior. 118 // 119 // Example: 120 // 121 // // WRONG 122 // float f = 3.14159265358979; 123 // int i = reinterpret_cast<int&>(f); // Wrong 124 // int j = *reinterpret_cast<int*>(&f); // Equally wrong 125 // int k = *bit_cast<int*>(&f); // Equally wrong 126 // 127 // Reinterpret-casting results in undefined behavior according to the ISO C++ 128 // specification, section [basic.lval]. Roughly, this section says: if an object 129 // in memory has one type, and a program accesses it with a different type, the 130 // result is undefined behavior for most "different type". 131 // 132 // Using bit_cast on a pointer and then dereferencing it is no better than using 133 // reinterpret_cast. You should only use bit_cast on the value itself. 134 // 135 // Such casting results in type punning: holding an object in memory of one type 136 // and reading its bits back using a different type. A `bit_cast()` avoids this 137 // issue by copying the object representation to a new value, which avoids 138 // introducing this undefined behavior (since the original value is never 139 // accessed in the wrong way). 140 // 141 // The requirements of `absl::bit_cast` are more strict than that of 142 // `std::bit_cast` unless compiler support is available. Specifically, without 143 // compiler support, this implementation also requires `Dest` to be 144 // default-constructible. In C++20, `absl::bit_cast` is replaced by 145 // `std::bit_cast`. 146 #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L 147 148 using std::bit_cast; 149 150 #else // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L 151 152 template < 153 typename Dest, typename Source, 154 typename std::enable_if<sizeof(Dest) == sizeof(Source) && 155 std::is_trivially_copyable<Source>::value && 156 std::is_trivially_copyable<Dest>::value 157 #if !ABSL_HAVE_BUILTIN(__builtin_bit_cast) 158 && std::is_default_constructible<Dest>::value 159 #endif // !ABSL_HAVE_BUILTIN(__builtin_bit_cast) 160 , 161 int>::type = 0> 162 #if ABSL_HAVE_BUILTIN(__builtin_bit_cast) 163 inline constexpr Dest bit_cast(const Source& source) { 164 return __builtin_bit_cast(Dest, source); 165 } 166 #else // ABSL_HAVE_BUILTIN(__builtin_bit_cast) 167 inline Dest bit_cast(const Source& source) { 168 Dest dest; 169 memcpy(static_cast<void*>(std::addressof(dest)), 170 static_cast<const void*>(std::addressof(source)), sizeof(dest)); 171 return dest; 172 } 173 #endif // ABSL_HAVE_BUILTIN(__builtin_bit_cast) 174 175 #endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L 176 177 ABSL_NAMESPACE_END 178 } // namespace absl 179 180 #endif // ABSL_BASE_CASTS_H_