Ravid Goldenberg
Ravid Goldenberg

Reputation: 2299

Combine template and inheritance

I have got an assignment to implement a few kinds of containers in a template fashion in c++. All of this containers should provide an iterators with all sorts of operators overloading. I am pretty new to templates, in fact this will be my first real project in this subject.

And this is my question: Is using templates with inheritance a good idea in this case? Could it be done for both the container and the iterator? If so, what should i be aware of? What should i not do? Any help on the subject will be much appreciated.

Upvotes: 1

Views: 303

Answers (4)

Xaqq
Xaqq

Reputation: 4386

You should start by writing the simpler container: a stack. It is simple because a stack does not need an interator.

I wrote you a small example of a stack implemented on top of std::list, with some inheritance.

Try to write your own first, but you can look at this one as a example if you want to.

#include <iostream>
#include <list>

/* Here mainly to demonstrate inheritance by providing a stack interface */
template<typename T>
class IStack
{
public:

  virtual void push(const T &i) = 0;
  virtual T& pop() = 0;
};

template<typename T>
class Stack : public IStack<T>
{
private:
  std::list<T>  _internal;

public:
  virtual void push(const T &i)
  {
    _internal.push_back(i);
  }
  virtual T& pop()
  {
    T& tmp = _internal.back();
    _internal.pop_back();
    return tmp;
  }
};

EDIT: Renamed based class as pointed out by James.

Upvotes: -1

James Kanze
James Kanze

Reputation: 153909

Neither inheritance nor templates are goals, and neither is good or bad in itself. The question is: what problem are you trying to solve? The distinction according to the type contained in a container should be made by the template: there's no good solution for the return type if it is handled by inheritance. How you manage the containment, advancing an iterator and testing for the end are good candidates for inheritance, but it still depends somewhat on the design.

Upvotes: 3

Jan Herrmann
Jan Herrmann

Reputation: 2767

Before you start reinventing the wheel you should look at the containers in the standard and in boost (Multiindex, Pointer Container Library, Graph, ...) and try to adapt one.

Upvotes: 0

Balog Pal
Balog Pal

Reputation: 17163

You're starting in a wrong direction. First create some alternatives you think could work (with and without inheritance), then compare them for pros&cons.

Or if you can't come up with one party, that closes your question fro good.

If you're new to templates I suggest start with typedef int VALTYPE; and implement the container using that as regular class. Test it, and after you're finished you can replace the introduction so it will be template and VALTYPE a parameter.

Upvotes: 0

Related Questions