向量将派生的智能指针推回基础抽象的智能指针向量 class

Vector push back a derived smart pointer into a vector of smart pointers of a base abstract class

假设我有以下基础摘要类

class Worker {
    public:
      struct Details {
           std::string name;
      };
    public:
      virtual void work() = 0;

};
class Manager {
    public: 
      virtual ~Manager() = default;
      virtual void hire(Worker::Details details) = 0;
      virtual void fire(const Worker & worker) = 0;
};

然后我实现了这两个抽象 类:

class DerivedWorker : Worker {
    public:
      DerivedWorker(Worker::Details details) : details(details) {}
      
      void work() override {}
    private:
      Worker::Details details;
};
class Derived : Manager {
    public:
      Derived() {}
      void hire(Worker::Details details) override {
          workers.push_back(std::make_unique<DerivedWorker>(details));
      }
      void fire(const Worker & worker) override {}
    private:
      std::vector<std::unique_ptr<Worker>> workers;
};

为什么 workers.push_back(std::make_unique<DerivedWorker>(details) 会抛出编译器 error: no matching member function for call to 'push_back' 异常?

同样,你会如何对 workers.emplace_back(...) 做同样的事情?

push_back 不起作用,因为您忘记了继承 public。

可能 emplace_back 也有同样的问题,但您永远不应将 emplace_back 用于智能指针向量。