Question

Possible Duplicate:
Is it ok to cast a STL container with Base type to Derived type?

This should be a quick question... If I have a container, say an STL list, of a base class, is it possible to casts the entire container to a type of subclass? E.g.

[A inherits from base class B]

list<B*> list1;
list1.push_back(new A());

list<A*> list2 = list1;

The compiler is complaining: "conversion from std::vector<B*, std:allocator<B*> >' to non-scalar type 'std::vector<Bar*, ...>' requested."

Is this possible, or am I'm just screwing it up?

Was it helpful?

Solution

No. std::list<T> and std::list<U> are completely different, incompatible types, if std::is_same<T,U>::value is false, i.e if the type arguments T and U aren't same.

Use std::transform and do appropriate casting in the callback.

OTHER TIPS

No, this isn't directly possible because lists with different template types are completely unrelated containers.

If you know that all the items in list1 are actually the child class A then just make list1 contain them as such up front. If you don't know that they're all of the child class then the conversion you want to do is illegal.

What are you really trying to do here?

The safer way to do this is using std::transform.

But, since inside the implementation of std::list, T=A* or T=B* behaves the same way (both have the same size), a list has same inner structure than a list. So it is possible to do the following trick:

list<B*> list2 = *( reinterpret_cast< list<B*>* >(&list1) );

Note: My answer is informational, please stick with the std::transform approach. Also, I tested this with GCC and it works, but I am not sure if in others STDC++ implementation the list behave the same way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top