P4C
The P4 Compiler
Loading...
Searching...
No Matches
rtti_utils.h
1/*
2Copyright 2024-present Intel Corporation.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
19
20#ifndef LIB_RTTI_UTILS_H_
21#define LIB_RTTI_UTILS_H_
22
23#include <type_traits>
24
25#include "rtti.h"
26
27namespace P4::RTTI {
28
35template <typename T>
36struct has_rtti : std::is_base_of<RTTI::Base, T> {};
37
40template <typename T>
41inline constexpr const bool has_rtti_v = has_rtti<T>::value;
42
44template <typename... Ts>
45inline constexpr const bool all_have_rtti_v = (has_rtti_v<Ts> && ...);
46
52template <typename T, typename R = void>
53struct enable_if_has_rtti : std::enable_if<has_rtti_v<T>, R> {};
54
58template <typename... Ts>
59using enable_if_all_have_rtti_t = std::enable_if_t<all_have_rtti_v<Ts...>, void>;
60
66template <typename T, typename R = void>
67using enable_if_has_rtti_t = typename enable_if_has_rtti<T, R>::type;
68
69namespace Detail {
70
71template <typename To, typename = enable_if_has_rtti_t<To>>
72struct ToType {
73 template <typename From, typename = enable_if_has_rtti_t<From>>
74 To *operator()(From *obj) const {
75 return obj ? obj->template to<To>() : nullptr;
76 }
77
78 template <typename From, typename = enable_if_has_rtti_t<From>>
79 const To *operator()(const From *obj) const {
80 return obj ? obj->template to<To>() : nullptr;
81 }
82};
83
84template <typename... Targets>
85// TODO(C++20): use concepts to check enable_if_all_have_rtti_t<Targets...>> & that there is at
86// least 1 target type.
87struct IsType {
88 static_assert(sizeof...(Targets) > 0,
89 "At least one target type needs to be given for RTTI::is");
90 static_assert(all_have_rtti_v<Targets...>,
91 "All types in RTTI::is<Ts> need to be custom-rtti-enabled");
92
93 template <typename From, typename = enable_if_has_rtti_t<From>>
94 bool operator()(const From *obj) const {
95 return obj && (obj->template is<Targets>() || ...);
96 }
97};
98
99} // namespace Detail
100
116template <typename To>
117inline const Detail::ToType<To> to;
118
130template <typename Target>
131inline const Detail::IsType<Target> is;
132
142template <typename... Targets>
143inline const Detail::IsType<Targets...> isAny;
144
145} // namespace P4::RTTI
146
147#endif // LIB_RTTI_UTILS_H_
Definition rtti_utils.h:87
Definition rtti_utils.h:72
Definition rtti_utils.h:53
Definition rtti_utils.h:36