C++ Generic Linked List

前端 未结 4 1285
旧巷少年郎
旧巷少年郎 2021-01-29 00:38

For the code below:

#include 
#include 

using namespace std;

class Foo2;
class Foo3;

template 
class Foo1 {
  pub         


        
相关标签:
4条回答
  • 2021-01-29 01:00

    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;
    }
    
    0 讨论(0)
  • 2021-01-29 01:06

    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.

    0 讨论(0)
  • 2021-01-29 01:07

    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.

    0 讨论(0)
  • 2021-01-29 01:21

    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...

    0 讨论(0)
提交回复
热议问题