ITK  6.0.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 #include <cstring> // For memcpy.
23 #include <type_traits> // For is_trivially_copyable and remove_const_t.
24 
25 namespace itk
26 {
27 
31 template <typename TDestination, class TSource>
32 TDestination
33 bit_cast(const TSource & source)
34 {
35  static_assert(sizeof(TDestination) == sizeof(TSource),
36  "The destination type should have the same size as the source type.");
37  static_assert(std::is_trivially_copyable_v<TDestination>, "The destination type should be trivially copyable");
38  static_assert(std::is_trivially_copyable_v<TSource>, "The source type should be trivially copyable.");
41  std::remove_const_t<TDestination> result;
42  std::memcpy(&result, &source, sizeof(TSource));
43  return result;
44 }
45 
46 } // namespace itk
47 
48 
49 #endif // itkBitCast_h
itk::bit_cast
TDestination bit_cast(const TSource &source)
Definition: itkBitCast.h:33
itk
The "itk" namespace contains all Insight Segmentation and Registration Toolkit (ITK) classes....
Definition: itkAnatomicalOrientation.h:29