P4C
The P4 Compiler
Loading...
Searching...
No Matches
rtti_utils.h
1/*
2 * SPDX-FileCopyrightText: 2024 Intel Corporation.
3 * Copyright 2024-present Intel Corporation.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
10
11#ifndef LIB_RTTI_UTILS_H_
12#define LIB_RTTI_UTILS_H_
13
14#include <type_traits>
15
16#include "rtti.h"
17
18namespace P4::RTTI {
19
26template <typename T>
27struct has_rtti : std::is_base_of<RTTI::Base, T> {};
28
31template <typename T>
32inline constexpr const bool has_rtti_v = has_rtti<T>::value;
33
35template <typename... Ts>
36inline constexpr const bool all_have_rtti_v = (has_rtti_v<Ts> && ...);
37
43template <typename T, typename R = void>
44struct enable_if_has_rtti : std::enable_if<has_rtti_v<T>, R> {};
45
49template <typename... Ts>
50using enable_if_all_have_rtti_t = std::enable_if_t<all_have_rtti_v<Ts...>, void>;
51
57template <typename T, typename R = void>
58using enable_if_has_rtti_t = typename enable_if_has_rtti<T, R>::type;
59
60namespace Detail {
61
62template <typename To, typename = enable_if_has_rtti_t<To>>
63struct ToType {
64 template <typename From, typename = enable_if_has_rtti_t<From>>
65 To *operator()(From *obj) const {
66 return obj ? obj->template to<To>() : nullptr;
67 }
68
69 template <typename From, typename = enable_if_has_rtti_t<From>>
70 const To *operator()(const From *obj) const {
71 return obj ? obj->template to<To>() : nullptr;
72 }
73};
74
75template <typename... Targets>
76// TODO(C++20): use concepts to check enable_if_all_have_rtti_t<Targets...>> & that there is at
77// least 1 target type.
78struct IsType {
79 static_assert(sizeof...(Targets) > 0,
80 "At least one target type needs to be given for RTTI::is");
81 static_assert(all_have_rtti_v<Targets...>,
82 "All types in RTTI::is<Ts> need to be custom-rtti-enabled");
83
84 template <typename From, typename = enable_if_has_rtti_t<From>>
85 bool operator()(const From *obj) const {
86 return obj && (obj->template is<Targets>() || ...);
87 }
88};
89
90} // namespace Detail
91
107template <typename To>
108inline const Detail::ToType<To> to;
109
121template <typename Target>
122inline const Detail::IsType<Target> is;
123
133template <typename... Targets>
134inline const Detail::IsType<Targets...> isAny;
135
136} // namespace P4::RTTI
137
138#endif // LIB_RTTI_UTILS_H_
Definition rtti_utils.h:78
Definition rtti_utils.h:63
Definition rtti_utils.h:44
Definition rtti_utils.h:27