FE 0.6.0
A header-only C++ library for writing frontends
Loading...
Searching...
No Matches
cast.h
Go to the documentation of this file.
1#pragma once
2
3#include "fe/assert.h"
4
5namespace fe {
6
7template<class T>
8concept Nodeable = requires(T n) {
9 T::Node;
10 n.node();
11};
12
13/// Inherit from this class using [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern),
14/// for some nice `dynamic_cast`-style wrappers.
15template<class B> class RuntimeCast {
16public:
17 // clang-format off
18 /// `static_cast` with debug check.
19 template<class T> T* as() { assert(isa<T>()); return static_cast<T*>(this); }
20
21 /// `dynamic_cast`.
22 /// If @p T isa fe::Nodeable, it will use `node()`, otherwise a `dynamic_cast`.
23 template<class T>
24 T* isa() {
25 if constexpr (Nodeable<T>) {
26 return static_cast<B*>(this)->node() == T::Node ? static_cast<T*>(this) : nullptr;
27 } else {
28 return dynamic_cast<T*>(static_cast<B*>(this));
29 }
30 }
31
32 /// Yields `B*` if it is *either* @p T or @p U and `nullptr* otherwise.
33 template<class T, class U> B* isa() { return (isa<T>() || isa<U>()) ? static_cast<B*>(this) : nullptr; }
34
35 template<class T > const T* as() const { return const_cast<RuntimeCast*>(this)->template as<T >(); } ///< `const` version.
36 template<class T > const T* isa() const { return const_cast<RuntimeCast*>(this)->template isa<T >(); } ///< `const` version.
37 template<class T, class U> const B* isa() const { return const_cast<RuntimeCast*>(this)->template isa<T, U>(); } ///< `const` version.
38 // clang-format on
39};
40
41} // namespace fe
Inherit from this class using CRTP, for some nice dynamic_cast-style wrappers.
Definition cast.h:15
T * as()
static_cast with debug check.
Definition cast.h:19
T * isa()
dynamic_cast.
Definition cast.h:24
const T * isa() const
const version.
Definition cast.h:36
B * isa()
Yields B* if it is either T or U and `nullptr* otherwise.
Definition cast.h:33
const B * isa() const
const version.
Definition cast.h:37
const T * as() const
const version.
Definition cast.h:35
Definition arena.h:9