Jan Rüegg Jan Rüegg - 2 months ago 20
C++ Question

vector of unique_ptr, inheritance?

Assuming this code:

class Parent {}
class Child : public Parent {}

static std::vector<std::unique_ptr<Child>> Foo();


Is there a simpler way to write this function:

std::vector<std::unique_ptr<Parent>> Bar() {
auto children = Foo();

std::vector<std::unique_ptr<Parent>> parents;
result.insert(result.end(), std::make_move_iterator(children.begin()),
std::make_move_iterator(children.end()));
return parents;
}


This doesn't work:

std::vector<std::unique_ptr<Parent>> Bar() {
return Foo(); // Compiler error: cannot convert from vector<...> to vector<...>
}

Answer

The types are different. Foo() returns std::vector<std::unique_ptr<Child>> while Bar() returns std::vector<std::unique_ptr<Parent>>. There's no way to circumvent that. However, rather than:

std::vector<std::unique_ptr<Parent>> Bar() {
    auto children = Foo();

    std::vector<std::unique_ptr<Parent>> parents;
    result.insert(result.end(), std::make_move_iterator(children.begin()),
                std::make_move_iterator(children.end()));
    return parents;
}

You can do:

std::vector<std::unique_ptr<Parent>> Bar() {
    auto tmp = Foo();
    return {std::make_move_iterator(tmp.begin()), std::make_move_iterator(tmp.end()));}
}
Comments