c – 如何在子类中重载模板化函数(专用)?
我有一个带有模板化函数的基类,它具有一般模板类型,以及专用版本.
#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:错误:没有在aChildClass中声明的成员函数atemplateFunction 如果我将“重载”功能更改为: template<> void baseClass::templateFunction(Type1 & t) { cout << "We overloaded the specialized template function for type 1!" << endl; } 我明白了: 如何正确地重载子类中的专用模板函数? 供参考,主要: #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建议的那样,使类本身模板,然后在子类中覆盖所需的方法(现在不是模板). 但我相信有人会想出更好的主意…… =) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |