类模板继承 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12895775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class template inheritance C++
提问by DropDropped
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.
我想问你如何正确地做到这一点,或者是否有另一种方法来做到这一点。谢谢。
回答by Rudolfs Bundulis
When inheriting you must show how to instantiate the parent template, if same template class T can be used do this:
继承时,您必须展示如何实例化父模板,如果可以使用相同的模板类 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);
}
};
If something else is needed just change the line:
如果需要其他东西,只需更改行:
class InsertItem2 : InsertItem<needed template type here>