C++类模板继承

24

我想从模板类继承,并在调用运算符"()"时更改行为 - 我想调用另一个函数。这段代码

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);
 }
};

出现了以下错误:

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

我想请问您如何正确地做这件事,或者是否有其他方法可以做到这一点。谢谢。


11
插入项目2: 插入项目<T> - Xeo
20
我不明白为什么人们要在评论中写答案…… - Mark Ingram
1
@MarkIngram,因为他们觉得没有必要写一个完整的答案。有什么不理解的呢? - avakar
5
@Mark:对于这么简单的问题,我懒得写一篇完整的答案 : ) 如果我还在追求声望的日子里,我会迫切需要像这样的问题,但现在不再了。我会让其他人获得声望,而且只要我完成我的简短评论(通常比写一篇完整的答案更快),提问者就能得到他的答案。 - Xeo
好的,我只是测试了一下你的评论是否会被接受为答案(因为它很简短),而且它确实被接受了,所以我想这可以让你少滚动几行代码 ;)。 - Mark Ingram
1
@Mark:嗯,我确实说过“写一个完整的答案”。我不认为我的评论内容是一个完整的答案,这就解释了为什么你需要它。此外,我很乐意把这样简单的问题的声望让给其他比我更需要的用户。 :) - Xeo
1个回答

35

当继承时,你必须展示如何实例化父模板,如果可以使用相同的模板类T,请按如下方式操作:

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);
    }
};

如果需要其他的东西,只需更改这一行即可:
class InsertItem2 : InsertItem<needed template type here>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接