【问题标题】:Class template inheritance C++类模板继承 C++
【发布时间】:2012-10-05 10:27:40
【问题描述】:

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

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

我想问您如何正确执行此操作,或者是否有其他方法可以执行此操作。谢谢。

【问题讨论】:

  • InsertItem2 : InsertItem&lt;T&gt;
  • 我一直不明白为什么人们把答案写在 cmets...
  • @MarkIngram,因为他们不想写一个完整的答案。有什么不明白的?
  • @Mark:不能为这么简单的事情写一个完整的答案。 :) 如果我还处于repwhoring 的日子,我会渴望这样的问题,但现在不会了。一旦我完成我的简短评论(这通常比写完整答案要快),我会让其他人接受代表,并且 OP 有他的答案。
  • @Mark:嗯,我确实说过“写一个完整的答案”。我不认为我评论中的内容是一个完整的答案,这可以解释你为什么需要它。此外,我很乐意将此类简单问题的代表提供给比我更需要它的其他用户。 :)

标签: c++ templates inheritance operators


【解决方案1】:

继承时必须说明如何实例化父模板,如果可以使用相同的模板类 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多