How do I check a dynamic_cast is successful when returning it from a function?

Viewed 60

I have a class which holds a vector of unique_ptrs, this class is to simplify polymorphism for me. I am trying to make a function which casts the base type to the derived type, but I can't work out how to pass back a value which I can then check to ensure it has worked (similar to if(dynamic_cast<>()...)

template <typename T>
class Vector_UniquePtrs {

public:
    template<typename U>
    U& DynamicCast(size_t i) { 
        return dynamic_cast<U&>(*m_Items[i]); 
    }

private:
    std::vector<std::unique_ptr<T>> m_Items;
}


Vector_UniquePtrs<Base> v;

if(auto a = v.DynamicCast<Derived>(0)) { // want to do something along these lines
    // success
} else {
    // fail
}

What is a nice way of achieving this? Thanks

1 Answers

If you are willing to return a pointer, then you can do

if(auto* a = v.DynamicCast<Derived>(0); a)

or the longer explicit version

if(auto* a = v.DynamicCast<Derived>(0); a!=nullptr)

Related