Search code examples
c++templatesdowncast

Downcast to template class


I've got template class and I wanted to have vector of this class type. I saw solution where you need to wrap the class with another class without template, and then have a vector of this new class. Now I want to downcast for example one of the list objects - but the cast not allowed. What should I do?

Example:

class Wrapper
{
}

template <typename T>
class Father : public Wrapper
{
}

int main()
{
    std::vector<std::shared_ptr<Wrapper>> objects;
    Father<int> object = (Father<int>)objects.at(0); // ERROR (lets say i know its integer)
}

Solution

  • objects[0] is a pointer to an object. Your cast (never use C-style casts by the way) attempts to convert the shared_ptr<Wrapper> object to a Father<int> object. That's not possible, of course, since those two types are wholly unrelated.

    Dereference the pointer and downcast it to a reference (if you want polymorphism):

    auto& object = static_cast<Father<int>&>(*objects[0]);