gdbsupport: add support for references to checked_static_cast

Add a checked_static_cast overload that works with references.  A bad
dynamic cast with references throws std::bad_cast, it would be possible
to implement the new overload based on that, but it seemed simpler to
just piggy back off the existing function.

I found some potential uses of this new overload in amd-dbgapi-target.c,
update them to illustrate the use of the new overload.  To build
amd-dbgapi-target.c, on needs the amd-dbgapi library, which I don't
expect many people to have.  But I have it, and it builds fine here.  I
did test the new overload by making a purposely bad cast and it did
catch it.

Change-Id: Id6b6a7db09fe3b4aa43cddb60575ff5f46761e96
Reviewed-By: Lancelot SIX <lsix@lancelotsix.com>
Reviewed-By: Andrew Burgess <aburgess@redhat.com>
This commit is contained in:
Simon Marchi
2023-05-18 15:05:56 -04:00
parent cbd9efbbc0
commit 175ee55a22
2 changed files with 35 additions and 9 deletions

View File

@@ -66,6 +66,22 @@ checked_static_cast (V *v)
return result;
}
/* Same as the above, but to cast from a reference type to another. */
template<typename T, typename V, typename = gdb::Requires<std::is_reference<T>>>
T
checked_static_cast (V &v)
{
static_assert (std::is_reference<T>::value, "target must be a reference type");
using T_no_R = typename std::remove_reference<T>::type;
using T_P = typename std::add_pointer<T_no_R>::type;
using V_no_R = typename std::remove_reference<V>::type;
return *checked_static_cast<T_P, V_no_R> (&v);
}
}
#endif /* COMMON_GDB_CHECKED_DYNAMIC_CAST_H */