P4C
The P4 Compiler
Loading...
Searching...
No Matches
castable.h
1/*
2 * SPDX-FileCopyrightText: 2022 VMware, Inc.
3 * Copyright 2022-present VMware, Inc.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIB_CASTABLE_H_
9#define LIB_CASTABLE_H_
10
11#include <typeinfo>
12
13#include "lib/exceptions.h"
14#include "lib/rtti.h"
15
16namespace P4 {
17
27class ICastable : public virtual RTTI::Base {
28 public:
29 virtual ~ICastable() = default;
30
32 template <typename T>
33 const T &as() const {
34 return *checkedTo<T>();
35 }
36
38 template <typename T>
39 T &as() {
40 return *checkedTo<T>();
41 }
42
44 template <typename T>
45 const T *checkedTo() const {
46 auto *result = to<T>();
47 BUG_CHECK(result, "Cast failed: %1% is not a %2%", this, typeid(T).name());
48 return result;
49 }
50
52 template <typename T>
53 T *checkedTo() {
54 auto *result = to<T>();
55 BUG_CHECK(result, "Cast failed: %1% is not a %2%", this, typeid(T).name());
56 return result;
57 }
58};
59
60} // namespace P4
61
62#endif /* LIB_CASTABLE_H_ */
Definition castable.h:27
T & as()
Tries to convert the class to type T. A BUG occurs if the cast fails.
Definition castable.h:39
const T * checkedTo() const
Performs a checked cast. A BUG occurs if the cast fails.
Definition castable.h:45
const T & as() const
Tries to convert the class to type T. A BUG occurs if the cast fails.
Definition castable.h:33
T * checkedTo()
Performs a checked cast. A BUG occurs if the cast fails.
Definition castable.h:53
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:13
Definition rtti.h:203
T * to() noexcept
Definition rtti.h:226