Trying to assign vector of Base* from vector of Derived*

前端 未结 3 1940
谎友^
谎友^ 2020-12-11 01:45

This seems like a pretty basic problem, but I can\'t figure it out. I have a std::vector of raw pointers to Derived objects, and I just want to copy it to anot

相关标签:
3条回答
  • 2020-12-11 02:21

    push_back performs element-wise conversions. The assignment operator exists only between vectors of the same type.

    An easy solution is to use assign:

    v2.assign(v1.begin(), v1.end());
    
    0 讨论(0)
  • 2020-12-11 02:21

    In the general case of templates, if you have a class template

    template <typename T> struct Foo {};
    

    Foo<Base> is not a base class of Foo<Derived>.

    Hence, you cannot do:

    Foo<Derived> f1;
    Foo<Base> f2 = f1;
    
    0 讨论(0)
  • 2020-12-11 02:28

    That's because while Base and Derived have a relationship, there is no relationship between vector<Base*> and vector<Derived*>. As far as class hierarchy is concerned, they are entirely unrelated, so you can't assign one to the other.

    The concept you are looking for is called covariance. In Java for instance, String[] is a subtype of Object[]. But in C++, these two types are just different types and are no more related than String[] and Bar.

    push_back works because that method just takes a T const& (or T&&), so anything convertible to a Base* will be acceptable - which a Derived* is.

    That said, vector has a constructor that takes a pair of iterators, which should be easier to use here:

    vector<Base*> v2(v1.begin(), v1.end());
    

    Or, since it is already constructed:

    v2.assign(v1.begin(), v1.end());
    
    0 讨论(0)
提交回复
热议问题