类模板继承C ++ [英] Class template inheritance C++

查看:455
本文介绍了类模板继承C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想继承模板类,并在调用操作符()时更改行为 - 我想调用另一个函数。此代码

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

给我这个错误:

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.

推荐答案

继承时必须显示如何实例化父模板,如果可以使用相同的模板类T,

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>

这篇关于类模板继承C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆