铸造容器C ++ [英] Casting containers C++
问题描述
可能重复:
是否可以将基本类型的STL容器转换为派生类型?
Possible Duplicate:
Is it ok to cast a STL container with Base type to Derived type?
这应该是一个快速的问题...如果我有一个基类的容器,例如STL列表,是否可以将整个容器转换为子类类型?例如
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;
编译器在抱怨:"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?
推荐答案
否.如果std::is_same<T,U>::value
是false
,即T
和U
的类型参数不同,则std::list<T>
和std::list<U>
是完全不兼容的类型.
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.
使用std::transform
并在回调中进行适当的转换.
Use std::transform
and do appropriate casting in the callback.
这篇关于铸造容器C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!