From fc20e61e7249006247b43f84a3189d5a37fa103e Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 20 Jan 2025 11:17:23 -0500 Subject: [PATCH] AK: Introduce an as_if() cast We currently have a fair amount of code of the form: if (is(parent)) { auto& child = static_cast(parent); if (child.foo()) { } } This new cast allows us to instead write code of the form: if (auto* child = as_if(parent); child && child->foo()) { } N.B. The name "as_if" was chosen because we are considering renaming verify_cast to "as". Co-authored-by: Tim Ledbetter --- AK/TypeCasts.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/AK/TypeCasts.h b/AK/TypeCasts.h index c076f5cae84..1b0721bef18 100644 --- a/AK/TypeCasts.h +++ b/AK/TypeCasts.h @@ -51,9 +51,26 @@ ALWAYS_INLINE CopyConst& verify_cast(InputType& input) return static_cast&>(input); } +template +ALWAYS_INLINE CopyConst* as_if(InputType& input) +{ + if (!is(input)) + return nullptr; + return static_cast*>(&input); +} + +template +ALWAYS_INLINE CopyConst* as_if(InputType* input) +{ + if (!input) + return nullptr; + return as_if(*input); +} + } #if USING_AK_GLOBALLY +using AK::as_if; using AK::is; using AK::verify_cast; #endif