P4C
The P4 Compiler
Loading...
Searching...
No Matches
castable.h
1/*
2Copyright 2022-present VMware, Inc.
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
17#ifndef LIB_CASTABLE_H_
18#define LIB_CASTABLE_H_
19
20#include <typeinfo>
21
22#include "lib/exceptions.h"
23#include "lib/rtti.h"
24
25namespace P4 {
26
36class ICastable : public virtual RTTI::Base {
37 public:
38 virtual ~ICastable() = default;
39
41 template <typename T>
42 const T &as() const {
43 return *checkedTo<T>();
44 }
45
47 template <typename T>
48 T &as() {
49 return *checkedTo<T>();
50 }
51
53 template <typename T>
54 const T *checkedTo() const {
55 auto *result = to<T>();
56 BUG_CHECK(result, "Cast failed: %1% is not a %2%", this, typeid(T).name());
57 return result;
58 }
59
61 template <typename T>
62 T *checkedTo() {
63 auto *result = to<T>();
64 BUG_CHECK(result, "Cast failed: %1% is not a %2%", this, typeid(T).name());
65 return result;
66 }
67};
68
69} // namespace P4
70
71#endif /* LIB_CASTABLE_H_ */
Definition castable.h:36
T & as()
Tries to convert the class to type T. A BUG occurs if the cast fails.
Definition castable.h:48
const T * checkedTo() const
Performs a checked cast. A BUG occurs if the cast fails.
Definition castable.h:54
const T & as() const
Tries to convert the class to type T. A BUG occurs if the cast fails.
Definition castable.h:42
T * checkedTo()
Performs a checked cast. A BUG occurs if the cast fails.
Definition castable.h:62
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:24
Definition rtti.h:203
T * to() noexcept
Definition rtti.h:226