用于导出的Base unique_ptr的向量

时间:2016-11-29 17:57:30

标签: c++ c++11 vector stl

我正在尝试下面的代码来创建Base类的向量并动态分配派生类。

#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>

class Base {

public:
  Base(int value) : item(value) {}
  int item;
};

class Derived : public Base {

public:
  Derived() : Base(0) {}
};

class Fac {
public:
  int count;
  std::vector<std::unique_ptr<Base>> m_BaseObj;

  void add(int data) {
    count++;
    m_BaseObj.push_back(std::unique_ptr<Base>(new Derived()));
    int index = (m_BaseObj.size() - 1);
    std::cout << "Index=" << index << std::endl;
    m_BaseObj[index].get()->item = data;
  }

  void display() {
    for (auto &Obj : m_BaseObj) {
      std::cout << Obj.get()->item << "  ";
    }
    std::cout << std::endl;
  }
  void deleteList() {
    int it;
    std::cout << "Enter item to delete:";
    std::cin >> it;
    int index = 0;
    m_BaseObj.erase(std::remove_if(m_BaseObj.begin(), m_BaseObj.end(),
                                   [it](const std::unique_ptr<Derived> &e) {
                                     return it == e->item;
                                   }),
                    m_BaseObj.end());
  }
};

int main() {
  Fac obj;
  int ch;
  obj.count = 0;
  while (1) {
    std::cout << "1. Add  2. Remove 3. Display\n";
    std::cin >> ch;
    switch (ch) {
    case 1:
      int data;
      std::cout << "Data: ";
      std::cin >> data;
      obj.add(data);
      obj.display();
      break;
    case 2:
      obj.deleteList();
      obj.display();
      break;
    case 3:
      obj.display();
      break;
    default:
      std::cout << "Invalid choice\n";
      exit(0);
    }
  }
}

这是为derive类分配时的编译错误。如果我为Derive创建,则代码似乎正常工作。

    In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from vector.cpp:4:
/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of â_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = __gnu_cxx::__normal_iterator<std::unique_ptr<Base>*, std::vector<std::unique_ptr<Base> > >; _Predicate = Fac::deleteList()::__lambda0]â:
vector.cpp:53:64:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:1150:33: error: no match for call to â(Fac::deleteList()::__lambda0) (std::unique_ptr<Base>&)â
         if(!bool(__pred(*__first)))
                                 ^
vector.cpp:52:48: note: candidate is:
         m_BaseObj.begin(), m_BaseObj.end(), [it](const std::unique_ptr<Derived>& e)
                                                ^
vector.cpp:52:83: note: Fac::deleteList()::__lambda0
         m_BaseObj.begin(), m_BaseObj.end(), [it](const std::unique_ptr<Derived>& e)

2 个答案:

答案 0 :(得分:2)

您对remove_if的谓词需要接受指向Base的指针,而不是Derived。你可以在里面进行施法。

编译器错误实际上非常清楚。

答案 1 :(得分:2)

std::remove_if需要将std::unique_ptr<Base>的元素类型传递给其谓词。但是你提供的谓词lambda需要一个const std::unique_ptr<Derived>&参数。这些是不同的类型,unique_ptr<Base>不能转换为unique_ptr<Derived>

修复你的lambda以const std::unique_ptr<Base>&作为参数。