1 // Copyright 2024 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_SRC_CORE_UTIL_DOWN_CAST_H
16 #define GRPC_SRC_CORE_UTIL_DOWN_CAST_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <type_traits>
21
22 #include "absl/base/config.h"
23 #include "absl/log/check.h"
24
25 namespace grpc_core {
26
27 template <typename To, typename From>
DownCast(From * f)28 GPR_ATTRIBUTE_ALWAYS_INLINE_FUNCTION inline To DownCast(From* f) {
29 static_assert(
30 std::is_base_of<From, typename std::remove_pointer<To>::type>::value,
31 "DownCast requires a base-to-derived relationship");
32 // If we have RTTI & we're in debug, assert that the cast is legal.
33 #if ABSL_INTERNAL_HAS_RTTI
34 #ifndef NDEBUG
35 if (f != nullptr) CHECK_NE(dynamic_cast<To>(f), nullptr);
36 #endif
37 #endif
38 return static_cast<To>(f);
39 }
40
41 template <typename To, typename From>
DownCast(From & f)42 GPR_ATTRIBUTE_ALWAYS_INLINE_FUNCTION inline To DownCast(From& f) {
43 return *DownCast<typename std::remove_reference<To>::type*>(&f);
44 }
45
46 } // namespace grpc_core
47
48 #endif // GRPC_SRC_CORE_UTIL_DOWN_CAST_H
49