|
Boost : |
From: Johan Nilsson (johan.nilsson_at_[hidden])
Date: 2002-12-10 10:14:13
"Terje Slettebø" <tslettebo_at_[hidden]> wrote in message
news:00e001c2a04e$92f9c190$60fb5dd5_at_pc...
> >From: "Johan Nilsson" <johan.nilsson_at_[hidden]>
>
>
> > The hack makes no 'fixed' assumptions on binary object
> > layout, rather, it relies on the fact that any polymorphic type can be
> > queried for an implemented interface (aka 'base class'). It does,
however,
> > make the assumption that the location of the rtti itself data is fixed
for
> a
> > specific c++ implementation across different polymorphic types.
> >
> > Sample usage (demonstrating syntax only):
> > --------------
> >
> > void foo(void*)
> > {
> > try
> > {
> > IMyBaseClass* pmc = dynamic_void_cast<IMyClass>(pv);
> >
> > if (pmc)
> > {
> > pmc-MyFn();
> > }
> > }
> > catch (std::exception&)
> > {}
> > }
> >
> >
> > The hack:
> > ------
> > template<typename T>
> > T* dynamic_void_cast(void* pv)
> > {
> > struct rtti_obj__
> > {
> > virtual ~rtti_obj__() = 0;
> > };
> >
> > rtti_obj__* pro = static_cast<rtti_obj__*>(pv);
> >
> > try
> > {
> > return dynamic_cast<T*>(pro);
> > }
> > catch (bad_cast&)
> > {
> > throw;
> > }
> > catch (exception& e)
> > {
> > throw bad_cast(e.what());
> > }
> > }
> >
> > ----------
>
> Why do you catch, and just rethrow exceptions? Why not just let them
> propagate (no try/catch), or turning them into return zero? Also, what
other
> exception, besides bad_cast, can dynamic_cast throw, which necessitates
the
> second catch clause?
This is rather platform specific, but in VC.NET, you can get the exception
__non_rtti_object (which is derived from bad_typeid)thrown as well. I
preferred throwing bad_cast exceptions only.
// Johan
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk