Boost logo

Boost :

From: Darren Kessner (dkessner_at_[hidden])
Date: 2002-05-03 13:04:42


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


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