diff --git a/include/tscore/ink_assert.h b/include/tscore/ink_assert.h index b9c2861dec2..bad4a86dc10 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(a); } +B & foo2(A &a) { return cast_to_derived(a); } +B const & foo3(A const &a) { return cast_to_derived(a); } -#undef assert -#define assert __DONT_USE_BARE_assert_USE_ink_assert__ -#define _ASSERT_H -#undef __ASSERT_H__ -#define __ASSERT_H__ */ + +template +Derived * +cast_to_derived(Base *b) // b must not be nullptr. +{ +#ifdef DEBUG + + ink_assert(b != nullptr); + auto d = dynamic_cast(b); + ink_assert(d != nullptr); + return d; + +#else + + return static_cast(b); + +#endif +} + +template +Derived & +cast_to_derived(Base &b) +{ +#ifdef DEBUG + + return dynamic_cast(b); + +#else + + return static_cast(b); + +#endif +} + +#endif /* __cplusplus */