CyberGK
CyberGK

Reputation: 47

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)
}

Upvotes: 1

Views: 654

Answers (2)

pscheid
pscheid

Reputation: 21

You don't need to wrap your template class to be able to create a vector with its type.

This will work just fine

std::vector<std::shared_ptr<Father<int>>> objects;
std::shared_ptr<Father<int>> object = objects.at(0);

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409404

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]);

Upvotes: 3

Related Questions