2

I have a linkedlist template to use, but I don't know how to use it or call the member functions.

template <class Object>
class List {
public:
    List();
    List(const List & rhs);
    ~List();

    bool isEmpty() const;

    void makeEmpty();
    ListItr<Object> zeroth() const;
    ListItr<Object> first() const;

    template <class Object> Object List<Object>::insert(const Object & x, const ListItr<Object> & p);
    ListItr<Object> find(const Object & x) const;
    ListItr<Object> findPrevious(const Object & x) const;

    void remove(const Object & x);
    const List & operator=(const List & rhs);
private:
    ListNode<Object> *header;
};

Is the line template <class Object> Object List<Object>::insert(const Object & x, const ListItr<Object> & p);the correct way to declare a member function? What exactly is it doing? And how do I call the functions and pass values to them to insert or remove from this list?

NikNik
  • 33
  • 4
  • 1
    This question is already answered in detail [here](https://stackoverflow.com/a/388282/3484570). Might require some time reading though. – nwp Jan 29 '18 at 23:27

1 Answers1

2

You should propbably read a tutorial about templates because these are relative trivial things for that.

However:

Templates are no classes, they generate classes at compile time.

template<class Object>
Class List {...};

The class in the <> is a placeholder for an actual type that you will pass in. It could be anything. (Note: you could also write typename instead of class, it is the same)

Beware though: It does not hold an object, it holds a type of the object.

You would create list objects like this:

List<int> list1;
List<double> list2;
List<MyOtherClass> list3;

Then they behave like normal object wherr you access the methods via the "." or "->" operator

The type of the template argument is known inside the class, and you don't have to explicitly call list of type Object as long as you are defining the methods inline in the class

Also declaring another template for a method inside a template class results in a second type argument that would be deduced by the parameters given to the function, they would be independent (or actually name clash, i am not sure since i'm on my phone)

Also: Keep in mind that you can't define template methods in a .cpp file, all content with templates must be in the .h file, otherwise the linker will throw errors

Plebshot
  • 210
  • 1
  • 9