This is an automated email from the ASF dual-hosted git repository.

wkaras pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficserver.git


The following commit(s) were added to refs/heads/master by this push:
     new 0350fc0  Add pointer/reference upcast function that is checked in 
debug builds. (#7582)
0350fc0 is described below

commit 0350fc078aa47e144b9db8a5296ce21da65cce02
Author: Walt Karas <[email protected]>
AuthorDate: Wed Mar 10 18:25:33 2021 -0600

    Add pointer/reference upcast function that is checked in debug builds. 
(#7582)
    
    Added to include/tscore/ink_assert.h.  Checking is disabled in release
    build for performance.
---
 include/tscore/ink_assert.h | 52 +++++++++++++++++++++++++++++++++++++++------
 1 file changed, 45 insertions(+), 7 deletions(-)

diff --git a/include/tscore/ink_assert.h b/include/tscore/ink_assert.h
index b9c2861..bad4a86 100644
--- a/include/tscore/ink_assert.h
+++ b/include/tscore/ink_assert.h
@@ -53,13 +53,51 @@ inkcoreapi void _ink_assert(const char *a, const char *f, 
int l) TS_NORETURN;
 
 #ifdef __cplusplus
 }
-#endif /* __cplusplus */
 
-/* workaround a bug in the  stupid Sun preprocessor
+/*
+Use cast_to_derived() to cast a pointer/reference to a dynamic base class into 
a pointer/reference to a class
+that inherits directly or indirectly from the base class.  Uses checked 
dynamic_cast in debug builds, and
+static_cast in release (optimized) builds.  Use examples:
+
+class A { public: virtual ~A(); };
+class B : public A {};
+B * foo(A *a) { return cast_to_derived<B>(a); }
+B & foo2(A &a) { return cast_to_derived<B>(a); }
+B const & foo3(A const &a) { return cast_to_derived<B const>(a); }
 
-#undef assert
-#define assert __DONT_USE_BARE_assert_USE_ink_assert__
-#define _ASSERT_H
-#undef __ASSERT_H__
-#define __ASSERT_H__
 */
+
+template <class Derived, class Base>
+Derived *
+cast_to_derived(Base *b) // b must not be nullptr.
+{
+#ifdef DEBUG
+
+  ink_assert(b != nullptr);
+  auto d = dynamic_cast<Derived *>(b);
+  ink_assert(d != nullptr);
+  return d;
+
+#else
+
+  return static_cast<Derived *>(b);
+
+#endif
+}
+
+template <class Derived, class Base>
+Derived &
+cast_to_derived(Base &b)
+{
+#ifdef DEBUG
+
+  return dynamic_cast<Derived &>(b);
+
+#else
+
+  return static_cast<Derived &>(b);
+
+#endif
+}
+
+#endif /* __cplusplus */

Reply via email to