我有一个带有模板函数的基类,该函数具有通用模板类型和专用版本。
#ifndef BASE_CLASS
#define BASE_CLASS
#include <iostream>
using namespace std;
struct Type1
{
};
struct Type2
{
};
class baseClass
{
public:
template<class Type>
void doStuff(Type & t)
{
templateFunction(t);
}
template<class Type>
void templateFunction(Type & t);
};
template<class Type>
void baseClass::templateFunction(Type & t)
{
cout << "This is the generic function!" << endl;
}
template<>
void baseClass::templateFunction(Type1 & t)
{
cout << "This is the specialized function: - Type1" << endl;
}
#endif
我还有一个子类,它继承自“baseClass”。但是,子类需要针对该特化的不同功能。
#ifndef CHILD_CLASS
#define CHILD_CLASS
#include "BaseClass.h"
class ChildClass : public baseClass
{
public:
};
template<>
void ChildClass::templateFunction(Type1 & t)
{
cout << "We overloaded the specialized template function for type 1!" << endl;
}
#endif
以上不编译:
ChildClass.h:13: 错误:“ChildClass”中没有声明成员函数“templateFunction” ChildClass.h:13: 错误:函数声明无效
如果我将“重载”函数更改为:
template<>
void baseClass::templateFunction(Type1 & t)
{
cout << "We overloaded the specialized template function for type 1!" << endl;
}
我得到: ChildClass.h:13: 错误:重新定义“void baseClass::templateFunction(Type&) [with Type = Type1]” BaseClass.h:36: error: âvoid baseClass::templateFunction(Type&) [with Type = Type1]â previously declared here
如何在子类中正确重载专门的模板函数?
供引用,主要有:
#include "BaseClass.h"
#include "ChildClass.h"
int main()
{
Type1 first;
Type2 second;
baseClass theBaseClass;
ChildClass theChildClass;
theBaseClass.doStuff(first);
theBaseClass.doStuff(second);
theChildClass.doStuff(first);
theChildClass.doStuff(second);
return 0;
}
根据 Kerrek SB 的建议,我将 ChildClass 更改为:
#ifndef CHILD_CLASS
#define CHILD_CLASS
#include "BaseClass.h"
class ChildClass : public baseClass
{
public:
template<class Type>
void templateFunction(Type & t);
};
template<>
void ChildClass::templateFunction(Type1 & t)
{
cout << "We overloaded the specialized template function for type 1!" << endl;
}
#endif
输出:
This is the specialized function: - Type1
This is the generic function!
This is the specialized function: - Type1
This is the generic function!
我希望:
This is the specialized function: - Type1
This is the generic function!
We overloaded the specialized template function for type 1!
This is the generic function!
所以这仍然行不通。
最佳答案
它仍然不能按您希望的方式工作的原因是该函数在父类中不是虚函数。但是,不可能有虚拟模板功能。
我看到两个主要选项:
- 按照 rhalbersma 的建议,将类本身设为模板,然后在子类中覆盖所需的方法(现在不是模板)。
- 对于专门的方法,只需编写一个新方法,使用不同的名称,它可以满足您的任何需要。
但我相信有人会想出更好的主意... =)
关于c++ - 如何在子类中重载模板函数(专门)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033267/