c++templatesdynamic-cast

c++ dynamic_cast of template argument type variable


Why does dynamic casting not work on a vector which specialized by template parameter type?

How can I solve this problem? I would like to determine from a vector whether the elements in it are descendants of a specific class?

class A {};
class B : public A {};

template<class _T_> void func(std::vector<_T_> &vect )
{
    A* pA = dynamic_cast<A*>( vect.data() );
    if( pA != nullptr) { /* I'm happy!*/ }
    else  { /* I'm sad! */   }
}

void main()
{
    std::vector<B> vectorOfB;
    func<B>( vectorOfB );
}

Solution

  • Thanks to everyone for the answers! They were very helpful.

    It was really a mistake to search for the base class with dynaic_cast.

    I found the answer to my problem in Jarod42's post: "Doesn't std::is_base_of<A, T> or std::is_convertible<T*, A*> (or other type_traits) do the job? – Jarod42 Sep 15 at 12:07"