UNPKG

1.55 kBtext/x-cView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4#pragma once
5#include <type_traits>
6#include <utility>
7
8namespace Microsoft::Common::Utilities {
9
10 // A simple wrapper for reinterpret_casting from TOriginalTypePtr to
11 // TResultTypePtr that does a static_assert before performing the cast. The
12 // usage syntax for this function is the same as the syntax for doing a regular
13 // reinterpret_cast. For example:
14 //
15 // uint32_t* i;
16 // auto p = CheckedReinterpretCast<char32_t*>(i);
17 //
18 template <typename TResultTypePtr, typename TOriginalTypePtr>
19 inline TResultTypePtr CheckedReinterpretCast(TOriginalTypePtr p) noexcept {
20 using TResultType = typename std::remove_pointer<TResultTypePtr>::type;
21 using TOriginalType = typename std::remove_pointer<TOriginalTypePtr>::type;
22
23 static_assert(
24 std::is_pointer<TResultTypePtr>::value && std::is_pointer<TOriginalTypePtr>::value &&
25 std::is_integral<TResultType>::value && std::is_integral<TOriginalType>::value &&
26 sizeof(TResultType) == sizeof(TOriginalType),
27 "CheckedReinterpretCast can only be used to cast from T1* to T2*, where "
28 "T1 and T2 are integral types of the same size.");
29
30 return reinterpret_cast<TResultTypePtr>(p);
31 }
32
33 // A compile time function that deduces the size of an array.
34 template <typename T, std::size_t N>
35 constexpr std::size_t ArraySize(T(&)[N]) noexcept {
36 return N;
37 }
38
39} // namespace Microsoft::Common::Utilities