c++ - unique_ptr 的 vector ,继承?

标签 c++ c++11 inheritance move-semantics

假设这段代码:

class Parent {}
class Child : public Parent {}

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

有没有更简单的方法来写这个函数:

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;
}

这行不通:

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

最佳答案

类型不同。 Foo()返回 std::vector<std::unique_ptr<Child>>同时Bar()返回 std::vector<std::unique_ptr<Parent>> .没有办法规避这一点。但是,而不是:

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;
}

你可以这样做:

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

关于c++ - unique_ptr 的 vector ,继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39746288/

相关文章:

c++ - 隐藏成员函数模板 - 哪个编译器是正确的?

c# - 如何使用单例进行继承

C++隐藏继承类?

c++ - Qsort 基于 c 字符串中的列?

c++ - 模板中右值引用和 const 左值引用之间的重载

c++ - 带虚函数的类的大括号初始化

c++ - 从元组派生类

Java编写库

c++ - 如何在 Arduino 中将 char 转换为 int

c++ - 与 std::unordered_map 的数据竞争,尽管使用互斥锁定插入