24

I'd like to inherit from the template class and change the behavior when the operators "()" are called - I want to call another function. This code

template<typename T>
class InsertItem
{
 protected:
 int counter;
 T   destination; 

 public:
  virtual void operator()(std::string item) {
     destination->Insert(item.c_str(), counter++);
  }

 public:
  InsertItem(T argDestination) {
          counter= 0;
    destination = argDestination;
  }
};

template<typename T>
class InsertItem2 : InsertItem
{
public:
 virtual void operator()(std::string item) {
  destination ->Insert2(item.c_str(), counter++, 0);
 }
};

gives me this error:

Error 1 error C2955: 'InsertItem' : use of class template requires template argument list...

I'd like to ask you how to do this properly, or if there is another way to do this. Thanks.

DropDropped
  • 1,253
  • 1
  • 22
  • 50
  • 11
    `InsertItem2 : InsertItem` – Xeo Oct 15 '12 at 12:34
  • 20
    I never understand why people write the answer in the comments... – Mark Ingram Oct 15 '12 at 12:38
  • 1
    @MarkIngram, because they don't feel like writing a full answer. What's there not to understand? – avakar Oct 15 '12 at 12:41
  • 5
    @Mark: Can't be arsed to write a full answer for something so simple. :) If I was still in my repwhoring days, I'd crave for questions like this, but not anymore. I'll let someone else take the rep and the OP has his answer as soon as I finish my short comment (which is usually faster than writing a full answer). – Xeo Oct 15 '12 at 12:43
  • Fair enough, I just tested whether your comment would be accepted as an answer (due to it's brevity), and it was, so I guess it saves you from scrolling an extra couple of lines ;). – Mark Ingram Oct 15 '12 at 14:46
  • 1
    @Mark: Well, I *did* say "writing a *full* answer". I don't consider the content in my comment a full answer, that would explain why you need it. Also, I gladly yield the rep for such simple questions to other users who need it more than me. :) – Xeo Oct 15 '12 at 22:26

1 Answers1

35

When inheriting you must show how to instantiate the parent template, if same template class T can be used do this:

template<typename T>
class InsertItem
{
protected:
    int counter;
    T   destination; 

public:
    virtual void operator()(std::string item) {
        destination->Insert(item.c_str(), counter++);
    }

public:
    InsertItem(T argDestination) {
        counter= 0;
        destination = argDestination;
    }
};

template<typename T>
class InsertItem2 : InsertItem<T>
{
public:
    virtual void operator()(std::string item) {
        destination ->Insert2(item.c_str(), counter++, 0);
    }
};

If something else is needed just change the line:

class InsertItem2 : InsertItem<needed template type here>
Morgoth
  • 4,935
  • 8
  • 40
  • 66
Rudolfs Bundulis
  • 11,636
  • 6
  • 33
  • 71