[LLVMdev] Small dyn_cast embellishment

Vladimir Prus
Thu, 17 Jun 2004 04:01:01 -0000

It appears that LLVM has quite a number of dyn_casts (which I find quite
natural) The suggested idiom:

   if (ConstantExpr* ce = dyn_cast<ConstantExpr>(*j)) {

   }

is fine, and IIRC even used in TC++PL, but it occured to me that we can do
even better:

   if (dyn_caster<ConstantExpr> ce = *j) {
   }

where dyn_caster is defined like this:

    template<class T>
    class dyn_caster
    {
    public:
        template<class T2>
        dyn_caster(T2& t)
        : m_ptr(dyn_cast<T>(t))
        {}

        T& operator*() const { return *m_ptr; }
        T* operator->() const { return m_ptr; }
        operator void*() const { return m_ptr; }
    private:
        T* m_ptr;
    };

This allows to type the type name only once, not twice. I'm not sure if this
good idea yet, but though I'd just throw it in, in case anybody will be
interested.

- Volodya