0

Consider the code snippet below:

#include <vector>

class Base {};
class Derived : public Base {};
std:vector<std:unique_ptr<Base>> baseVector;

I want to down-cast the vector to vector<unique_ptr<Derived>>

The naive approach would be:

  1. iterating over the baseVector
  2. for each element of type Base, dynamic_cast it to Derived class
  3. add a casted element to the new vector of type vector<unique_ptr<Derived>>

Is there a simple way to down-cast the baseVector to vector<unique_ptr<Derived>> all together (one line)?

user4581301
  • 33,082
  • 7
  • 33
  • 54
Andrey
  • 853
  • 9
  • 27
  • if you want one line, the best way imo is write a function to do it. – apple apple Aug 19 '22 at 17:27
  • maybe range library can help though. – apple apple Aug 19 '22 at 17:27
  • Downcasting is usually for chumps. Consider expanding the interface described by `Base` with virtual functions so that the user needs not know or care what exact class they're holding. – user4581301 Aug 19 '22 at 17:28
  • You've to create a new vector. The value type of your desired vector is different so you cannot naively downcast the same vector. You may use std::transform to create new vector. – madhur4127 Aug 19 '22 at 17:28
  • 3
    If every element in the vector is, in fact, `std::unique_ptr`, then just use `std::vector>` to start with. If there are elements that aren't pointers to `Derived` then nothing you do can validly turn the vector into a vector of pointers to `Derived`. In short, this sound like a **design** problem, not a coding problem. – Pete Becker Aug 19 '22 at 17:38

0 Answers0