ITK  5.3.0
Insight Toolkit
itkBitCast.h
Go to the documentation of this file.
1 /*=========================================================================
2  *
3  * Copyright NumFOCUS
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * https://www.apache.org/licenses/LICENSE-2.0.txt
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  *=========================================================================*/
18 
19 #ifndef itkBitCast_h
20 #define itkBitCast_h
21 
22 #if __cplusplus < 202002L
23 
24 # include <cstring> // For memcpy.
25 # include <type_traits> // For is_trivially_copyable and remove_const_t.
26 
27 namespace itk
28 {
29 
32 template <typename TDestination, class TSource>
33 TDestination
34 bit_cast(const TSource & source)
35 {
36  static_assert(sizeof(TDestination) == sizeof(TSource),
37  "The destination type should have the same size as the source type.");
38  static_assert(std::is_trivially_copyable<TDestination>::value, "The destination type should be trivially copyable");
39  static_assert(std::is_trivially_copyable<TSource>::value, "The source type should be trivially copyable.");
42  std::remove_const_t<TDestination> result;
43  std::memcpy(&result, &source, sizeof(TSource));
44  return result;
45 }
46 
47 } // namespace itk
48 
49 #else
50 
51 // From C++20, std::bit_cast is included with the C++ Standard Library.
52 # include <bit>
53 
54 namespace itk
55 {
57 }
58 
59 #endif
60 
61 #endif // itkBitCast_h
itk::bit_cast
TDestination bit_cast(const TSource &source)
Definition: itkBitCast.h:34
itk
The "itk" namespace contains all Insight Segmentation and Registration Toolkit (ITK) classes....
Definition: itkAnnulusOperator.h:24