Boost logo

Boost :

From: Itay (itay_maman_at_[hidden])
Date: 2002-05-03 14:54:43


You can modify your test() function such that it will work with boost::any
as-is:

void test(any thing)
{
    A** ppa = any_cast<A*>(&thing);
    if (ppa)
      (*ppa)->do_something();
}

(I didn't test this code, so no guarantee is given, but I believe it should
work as expected)

-Itay.

"Darren Kessner" <dkessner_at_[hidden]> wrote in message
news:20020503180442.99383.qmail_at_web11503.mail.yahoo.com...
> Hello,
>
> I've just recently discovered Boost, so please excuse
> me if this topic has been discussed already. I have a
> suggestion to make usage of boost::any for pointers
> more natural.
>
> My natural inclination is to use boost::any to hold
> different types of pointers. Then, I'd like to check
> the type of the pointer at run-time with behavior
> similar to dynamic_cast:
>
> void test(any thing)
> {
> A* pa = any_cast<A*>(thing);
> if (pa)
> pa->doSomething();
> }
>
> Unfortunately, any_cast throws bad_any_cast if thing
> is not an A*. In this way, the behavior of any_cast
> is similar to that of dynamic_cast, since thing is
> being passed by reference. But the behavior is
> dissimilar in that I (may) know that thing is really
> holding a pointer, so any_cast should return 0 instead
> of throwing.
>
> My suggestion is to add an any_ptr class that holds a
> pointer to something:
>
> class any_ptr
> {
> public:
>
> template<typename T>
> any_ptr(T* p)
> {
> thing_ = p;
> }
>
> any thing_; // public for illustration
> };
>
> Then any_cast can be overloaded to behave like
> dynamic_cast when passed an any_ptr:
>
> template<typename ValueTypePtr>
> ValueTypePtr any_cast(const any_ptr& operand)
> {
> ValueTypePtr p = 0;
>
> try {
> p = any_cast<ValueTypePtr>(operand.thing_);
> } catch (bad_any_cast){
> p = 0;
> }
>
> return p;
> }
>
> This works ok for me in simple tests, but I haven't
> looked at what issues there may be in detail.
>
>
> Darren
>
>
>
> __________________________________________________
> Do You Yahoo!?
> Yahoo! Health - your guide to health and wellness
> http://health.yahoo.com
> _______________________________________________
> Unsubscribe & other changes:
http://lists.boost.org/mailman/listinfo.cgi/boost
>


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