Boost logo

Boost :

From: Johan Nilsson (johan.nilsson_at_[hidden])
Date: 2002-12-10 07:35:00


"David Abrahams" <dave_at_[hidden]> wrote in message
news:ubs3u5f7c.fsf_at_boost-consulting.com...
> "Johan Nilsson" <johan.nilsson_at_[hidden]> writes:
>
> > [I've tried posting this to c.l.c++.m, but to no success. Don't know if
it's
> > due to some of the assert code looking like html markup ;-) or whatever.
> > Anyway, I thought this might also be a good forum.]
>
> Does this have something to do with C++ library writing? If so,
> please say what. If not, it's not an appropriate forum.

Yes, at least I hope so. See comments below.

[snip]

>
> A rather lengthy example with no comments or explanatory text
> describing what it's supposed to be accomplishing is not very easy to
> analyze. If you want feedback from the group, it would be polite to
> describe what you're trying to do.
>

I certainly wasn't being intentionally rude; apologies to anyone offended by
my posting.

I just wanted to get some feedback on what I tried, and currently consider
the stuff as a hack. But, as the functionality would be extremely helpful
for object factories, I thought I might as well post the code and get some
comments about it. 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());
  }
}

----------

I'll put together a sample showing some more concrete usage, this is more
something of an apologetic sample ;-)

// Johan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk