C++ Generic Linked List

时间秒杀一切 提交于 2019-12-02 08:27:51

I think the problem is the "?" in LinkedList

If this is the case, then you should use LinkedList<Foo1 *>.

Why can't you use std::list? Maybe we can help you with that, it will be far better that using your own implementation.

You need to use a T*, not a T. Looks to me like you came from Java where everything is a reference. There is no ? in C++ templates. I think that you need to pick up a book on basic C++ first, and then come back to templates.

Despite your assertions to the contrary, the example you've given could be solved with std::list:

std::list<Foo1 *> list;

list.push_back(new Foo2());
list.push_back(new Foo3());

for (std::iterator<Foo1 *> it = list.begin(); it != list.end(); ++it)
{
    (*it)->print();
}

Obviously, there's a potential memory leak here...

Combining the bits, it seems like this should work:

int main() {
  std::list<boost::variant<Foo2, Foo3> > list;
  list.push_back(Foo2());
  list.push_back(Foo3());
  printAll(list); // You'd still need to write this obviously.
  return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!