Here's a little utility I thought I'd share.
(For those familiar with ATL::CComQIPtr, the concept is similar).
====
#ifndef DYNPTR_H_INCLUDED
#define DYNPTR_H_INCLUDED
/*
DynPtr - A pointer with an implicit dynamic-cast
Purpose: When code requires a lot of dynamic_casting,
it can be difficult to read, so DynPtr is a pointer
that implicitly
dynamic_casts, to save the bother of writing dynamic_cast all
the time.
e.g.
Integer *i = dynamic_cast<Integer*>(value);
Integer *ci = dynamic_cast<const Integer*>(value);
vs
DynPtr<Integer> i(value);
DynPtr<const Integer> ci(value);
Written by Calum Grant. http://visula.org/calum
Public domain - free of copyright.
*/
template<class T>
class DynPtr
{
T *p;
public:
DynPtr() : p(0) { }
DynPtr(const DynPtr &q) : p(q.get()) { }
explicit DynPtr(T *q) : p(q) { }
template<class Q>
explicit DynPtr(const DynPtr<Q> &q) : p(dynamic_cast<T*>(q.get())) { }
template<class Q>
explicit DynPtr(Q *q) : p(dynamic_cast<T*>(q)) { }
DynPtr &operator=(const DynPtr &q) { p = q.get(); return *this; }
DynPtr &operator=(T *p) { p = q; return *this; }
template<class Q> DynPtr<T> &operator=(const DynPtr<Q> &q)
{
p = dynamic_cast<T*>(q.get());
return *this;
}
template<class Q> DynPtr<T> &operator=(Q *q)
{
p = dynamic_cast<T*>(q);
return *this;
}
operator bool() const { return p!=0; }
T *operator->() const { return p; }
T &operator*() const { return p; }
T *get() const { return p; }
};
#endif