c++ - 类模板继承 C++

标签 c++ templates inheritance operators

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

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

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

最佳答案

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

关于c++ - 类模板继承 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12895775/

相关文章:

c++ - C++ 中的自定义 list.sort 比较

c++ - GMP库函数

Angular 组件继承

java - 如何将单例引用传递给十个兄弟对象

c# - 从类继承并添加附加属性

c++ - 何时使用 shared_ptr 以及何时使用原始指针?

c++ - 通过引用返回的函数与返回 const 值的 const 函数之间的区别

c++ - 为自定义 C++ 类实现 Visual Studio 的自定义向导

C++ : template class vs two classes : efficiency

c++ - 在 C++ 中将函数作为参数执行